1. 程式人生 > >ZOJ 1610 Count the Colors(線段樹區間染色+區間統計)

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;
}