zoukankan      html  css  js  c++  java
  • HDU-1556-Color the ball (线段树和差分数组两种解法)

    N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?

    Input

    每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。 
    当N = 0,输入结束。

    Output

    每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。

    Sample Input

    3
    1 1
    2 2
    3 3
    3
    1 1
    1 2
    1 3
    0

    Sample Output

    1 1 1
    3 2 1

    题解:

    线段树版:

    代码:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #define maxn 50005
    using namespace std;
    int lazy[1000005],N;
    struct node
    {
    	int l,r,sum;
    }tr[1000005];
    void build(int m,int l,int r)
    {
    	tr[m].l=l;
    	tr[m].r=r;
    	tr[m].sum=0;
    	if(l!=r)
    	{
    		int mid=(l+r)>>1;
    		build(m<<1,l,mid);
    		build(m<<1|1,mid+1,r);
    	}
    }
    void insert(int m,int l,int r)
    {
    	if(tr[m].l==l&&tr[m].r==r)
    	{
    		tr[m].sum++;
    	}
    	else
    	{
    		int mid=(tr[m].l+tr[m].r)>>1;
    		if(r<=mid)
    		  insert(m<<1,l,r);
    		else if(l>mid)
    		{
    			insert(m<<1|1,l,r);
    		}
    		else
    		{
    			insert(m<<1,l,mid);
    			insert(m<<1|1,mid+1,r);
    		}
    	}
    }
    void add(int x)
    {
    	for(int i=tr[x].l;i<=tr[x].r;i++)
    	{
    		lazy[i]+=tr[x].sum;
    	}
    	if(tr[x].l==tr[x].r)
    	return;
    	add(x<<1);
    	add(x<<1|1);
    }
    int main()
    {
    	while(~scanf("%d",&N),N)
    	{
    		build(1,1,N);
    		for(int t=1;t<=N;t++)
    		{
    		int a,b;
    		scanf("%d%d",&a,&b);
    		insert(1,a,b);
    		}
    		memset(lazy,0,sizeof(lazy));
    		add(1);
    		printf("%d",lazy[1]);
    		for(int t=2;t<=N;t++)
    		{
    			printf(" %d",lazy[t]);
    		}
    		cout<<endl;
    	}
    	return 0; 
    }

    差分数组

    代码:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    
    using namespace std;
    
    int main()
    {
    	int f[100005]={0};
    	int a[100005]={0};
    	 
    	int n;
       while(cin>>n)
       {
       	if(n==0)
       	break;
       memset(f,0,sizeof(f));
       memset(a,0,sizeof(a));
    	int l,r;
    	for(int t=1;t<=n;t++)
    	{
    		scanf("%d%d",&l,&r);
    		f[l]++;
    		f[r+1]--;
    	}
    	for(int t=1;t<=n;t++)
    	{
    		a[t]=a[t-1]+f[t];
    	}
    	for(int t=1;t<n;t++)
    	{
    		printf("%d ",a[t]);
    	}
    	printf("%d
    ",a[n]);
       }
    	return 0;
    }
  • 相关阅读:
    android intent 隐式意图和显示意图(activity跳转)
    Stack栈的三种含义
    gdi+ 高速绘制透明窗体
    Hibernate Criterion
    iOS安全攻防(三):使用Reveal分析他人app
    Android入门第八篇之GridView(九宫图)
    【Android动画】之Tween动画 (渐变、缩放、位移、旋转)
    Ubuntu下deb包的安装方法
    理解class.forName()
    Myeclipse7.5 下载 安装 注冊 注冊码 100%成功
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10781928.html
Copyright © 2011-2022 走看看