ZOJ 1610 Count the Colors(线段树区间染色+区间统计)

题意:

在一条长度为8000的线段上染色,每次把区间[a,b]染成c颜色。显然,后面染上去的颜色会覆盖掉之前的颜色。

求染完之后,每个颜色在线段上有多少个间断的区间。

思路:

此题有个坑点,就是染色是染区间,而不是染点,什么意思呢?举个栗子,比如1 2 1,3 4 1([1,2]和[3,4]被染成1),最后查找的时候是按左到右叶子查找的,所以会把这两个区间当成连续的,实质上是间隔的([2,3]没有被染色),解决方法就是update的时候让x+1或y-1(y-1的时候要保证update的l参数是0而不是1,比如0 1 1,如果不从0开始找那么会忽略这个被染色的区间),这样就能保证区间是不连续的(左开右闭或左闭右开),最后统计区间得个数时用一个last变量保存上一个区间点的颜色,如果不一样就更新。还有就是col初始化为-1是因为有0这种颜色。

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=8005;
const int mod=1e9+7;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll qpow(ll a,ll b){ll t=1;while(b){if(b%2){t=(t*a)%mod;b--;}a=(a*a)%mod;b/=2;}return t;}
ll inv(ll a,ll p){return qpow(a,p-2);}
int col[maxn<<2],last=-1,ans[maxn];
void pushDown(int rt)
{
    if(col[rt]!=-1)
    {
        col[rt<<1]=col[rt<<1|1]=col[rt];
        col[rt]=-1;
    }
}
void update(int L,int R,int C,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        col[rt]=C;
        return ;
    }
    if(col[rt]==C)  return ;
    pushDown(rt);
    int m=(l+r)>>1;
    if(L<=m)    update(L,R,C,l,m,rt<<1);
    if(m<R)     update(L,R,C,m+1,r,rt<<1|1);
}
void query(int l,int r,int rt)
{
    if(l==r)
    {
        if(col[rt]!=-1&&col[rt]!=last)
        {
            ans[col[rt]]++;
        }
        last=col[rt];
        return ;
    }
    pushDown(rt);
    int m=(l+r)>>1;
    query(l,m,rt<<1);
    query(m+1,r,rt<<1|1);
}
int main()
{
    std::ios::sync_with_stdio(false);
    int n;
    while(cin>>n&&n)
    {
        memset(col,-1,sizeof(col));
        memset(ans,0,sizeof(ans));
        int x,y,c;
        last=-1;
        for(int i=0;i<n;i++)
        {
            cin>>x>>y>>c;
            update(x+1,y,c,1,maxn,1);
            //update(x,y-1,c,0,maxn,1);也可以
        }
        query(1,maxn,1);
        for(int i=0;i<maxn;i++)
        {
            if(ans[i])
            {
                cout<<i<<" "<<ans[i]<<endl;
            }
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dilly__dally/article/details/84678184
今日推荐