Description
Painting some colored segments on a line, some previously painted segments may be covered by some the subsequent ones.
Your task is counting the segments of different colors you can see at last.
Input
The first line of each data set contains exactly one integer n, 1 <= n <= 8000, equal to the number of colored segments.
Each of the following n lines consists of exactly 3 nonnegative integers separated by single spaces:
x1 x2 c
x1 and x2 indicate the left endpoint and right endpoint of the segment, c indicates the color of the segment.
All the numbers are in the range [0, 8000], and they are all integers.
Input may contain several data set, process to the end of file.
Output
Each line of the output should contain a color index that can be seen from the top, following the count of the segments of this color, they should be printed according to the color index.
If some color can't be seen, you shouldn't print it.
Print a blank line after every dataset.
Sample Input
5
0 4 4
0 3 1
3 4 2
0 2 2
0 2 3
4
0 1 1
3 4 1
1 3 2
1 3 1
6
0 1 0
1 2 1
2 3 1
1 2 0
2 3 0
1 2 1
Sample Output
1 1
2 1
3 1
1 1
0 2
1 1
错误点:在刚开始以为n就是树的最大范围了,然后一直报段错误(RE),后来发现maxn才是,解决后又wa了几次。还有就是(2,3,0)和(4,5,0)其实是两段,需要注意。
解题思路:区间替换、用线段树平常意义上的点代替长度为1的单位线段,统计段数。这里用到线段树只是为了保存哪些线段是什么颜色的,树中保存了一段一段的颜色,我们需要通过一次询问,把树上的颜色段拿出来,然后放在一条线上,某些区间什么颜色,这就已经不再跟线段树有关系了,就是平常的统计了。
#include<bits/stdc++.h> using namespace std; #define mid (L+R)/2 #define lson rt*2,L,mid #define rson rt*2+1,mid+1,R const int maxn = 10000; int colseg[maxn]; int cnt[maxn]; struct SegTree{ int col; }segs[maxn*4]; void buildtree(int rt,int L,int R){ segs[rt].col = 0; if(L == R){ return; } buildtree(lson); buildtree(rson); } void PushDown(int rt){ if(segs[rt].col){ segs[rt*2].col = segs[rt*2+1].col = segs[rt].col; segs[rt].col = 0; } } void Update(int rt,int L,int R,int l_ran,int r_ran,int _col){ if(l_ran <= L && R <= r_ran){ segs[rt].col = _col; return; } PushDown(rt); if(l_ran <= mid){ Update(lson,l_ran,r_ran,_col); } if(r_ran > mid){ Update(rson,l_ran,r_ran,_col); } } void query(int rt,int L,int R){ //把颜色段从树中拿出来,放入colseg数组中 if(segs[rt].col){ for(int i = L; i <= R; i++){ colseg[i] = segs[rt].col; } segs[rt].col = 0; return ; } if(L == R) return; query(lson); query(rson); } int main(){ int n, m; n = 8001; while(scanf("%d",&m)!=EOF){ memset(cnt,0,sizeof(cnt)); memset(colseg,0,sizeof(colseg)); buildtree(1,1,n); int u, v, w; for(int i = 1; i <= m; i++){ scanf("%d%d%d",&u,&v,&w); w++; u++; //把点都看成线段 Update(1,1,n,u,v,w); } query(1,1,n); for(int i = 1; i <= n+10; i++){ if(!colseg[i]) continue; int j; for(j = i; j <= n+10 && colseg[i]==colseg[j]; j++) ; cnt[colseg[i]]++; i = j - 1; //这里的点都是代表长度为1的单位线段 } for(int i = 1; i <= n+10; i++){ if(cnt[i]){ printf("%d %d ",i-1,cnt[i]); } }puts(""); } return 0; }