CODE[VS]1191 数轴染色

题目描述 Description

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

输入描述 Input Description

输入一行为NM。下面M行每行两个数LiRi

输出描述 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

解题思路:

      这道题目第一想到的便是线段树,将线段树稍稍变形即可完成此题。

      当然,这道题目也可以用并查集来做,效率比线段树稍慢,但内存要小的多。

代码:(请不要直接拷贝哦)


//并查集
#include <cstdio>
int n,m,x,y,fa[200005];
using namespace std;
inline int read()    
{    
    int f=1,x=0;    
    char ch=getchar();    
    if (ch=='-')    
    {    
        f=-1;    
        ch=getchar();    
    }    
    while ((ch<'0')||(ch>'9')) ch=getchar();    
    while ((ch>='0')&&(ch<='9'))    
    {    
        x=x*10+ch-48;    
        ch=getchar();    
    }    
    return f*x;    
}
inline int find(int x)
{
	if (fa[x]==x) return x;
	fa[x]=find(fa[x]);
	  return fa[x];
}
int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;i++) fa[i]=i;
	for (int i=1;i<=m;i++)
	{
		x=read(),y=read();
		while (find(y)!=find(x-1))
		{
			fa[find(y)]=fa[find(y)-1];
			n--;
		}
		printf("%d\n",n);
	}
	return 0;
}

//线段树
#include <cstdio>
int n,m,x,y;
using namespace std;
struct TREE{
	int l,r,sum;
	bool lazy;
}tree[800005];
inline int read()    
{    
    int f=1,x=0;    
    char ch=getchar();    
    if (ch=='-')    
    {    
        f=-1;    
        ch=getchar();    
    }    
    while ((ch<'0')||(ch>'9')) ch=getchar();    
    while ((ch>='0')&&(ch<='9'))    
    {    
        x=x*10+ch-48;    
        ch=getchar();    
    }    
    return f*x;    
}  
inline void build(int root,int l,int r)
{
	tree[root].l=l;
	tree[root].r=r;
	if (l==r)
	{
		tree[root].sum=1;
		return;
	}
	build(root*2,l,(l+r)/2);
	build(root*2+1,(l+r)/2+1,r);
	tree[root].sum=tree[root*2].sum+tree[root*2+1].sum;
}  
inline void change(int root,int l,int r)
{
	if (tree[root].lazy)
	{
		tree[root].sum=0;
		tree[root*2].lazy=1;
		tree[root*2+1].lazy=1;
		return;
	}
	int ll=tree[root].l,rr=tree[root].r;
	int mid=(ll+rr)/2;
	if ((ll==l)&&(rr==r))
	{
		tree[root].lazy=1;
		tree[root].sum=0;
		return;
	}
	if (l>mid) change(root*2+1,l,r); else
	  if (r<=mid) change(root*2,l,r); else
	  {
	  	change(root*2,l,mid);
	  	change(root*2+1,mid+1,r);
	  }
	tree[root].sum=tree[root*2].sum+tree[root*2+1].sum;	
}
int main()
{
	n=read(),m=read();
	build(1,1,n);
	for (int i=1;i<=m;i++)
	{
		x=read(),y=read();
		change(1,x,y);
		printf("%d\n",tree[1].sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhouhongkai06/article/details/79946763