codevs 1191【数轴染色】 并查集

题目描述 Description

在一条数轴上有N个点,分别是1~N。一开始所有的点都被染成黑色。接着
我们进行M次操作,第i次操作将[Li,Ri]这些点染成白色。请输出每个操作执行后
剩余黑色点的个数。

输入描述 Input Description

输入一行为N和M。下面M行每行两个数Li、Ri

输出描述 Output Description

输出M行,为每次操作后剩余黑色点的个数。

样例输入 Sample Input

10 3
3 3
5 7
2 8

样例输出 Sample Output

9
6
3

数据范围及提示 Data Size & Hint

数据限制
对30%的数据有1<=N<=2000,1<=M<=2000
对100%数据有1<=Li<=Ri<=N<=200000,1<=M<=200000
一眼线段树,虽然能过,不过太傻X了233
每次我们摧毁了一个区间,下一次如果还要摧毁这个区间或者它的子区间的话,我们就不用处理了。这样我们可以把每一个区间抽象成一个点,用并查集来维护。合并时将[L,R]区间全部合并,然后n–。这样每个点只会被合并一次,复杂度O(nα(n))
,跑得很快。
代码:
 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int fa[200010];
int find(int x)
{
&nbsp;&nbsp; &nbsp;return fa[x]==x?x:fa[x]=find(fa[x]);
}
int main()
{
    int n,m;
&nbsp;&nbsp; &nbsp;scanf(“%d%d”,&n,&m);
&nbsp;&nbsp; &nbsp;for(int i=0;i<=n;i++) fa[i]=i;
&nbsp;&nbsp; &nbsp;while(m–)
&nbsp;&nbsp; &nbsp;{
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;int x,y;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;scanf(“%d%d”,&x,&y);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;while(find(y)!=find(x-1)) fa[find(y)]=fa[find(y)-1],n–;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;printf(“%dn”,n);
&nbsp;&nbsp; &nbsp;}
    return 0;
}

/*
g++ codevs1191.cpp -o codevs1191.exe -Wall
*/
ZOJ 3811 Untrusted Patrol 并查集 染色 BFS
hdu5215 dfs染色判奇环+边双连通分量判偶环 并查集
codevs1073家族胡写并查集
CodeVS2492 上帝造题的七分钟2树状数组+并查集
codevs 1069关押罪犯 并查集

上一篇
下一篇