Count the Colors
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
思路
区间染色,每次将区间a ~ b染成颜色c,问最后每种颜色出现了多少次。连续的一段区间算一次颜色。虽然知道利用线段树维护,但是没想明白线段树怎么维护。
- 最开始是直接对区间[a,b]颜色染成c这种做法发现测试样例都过不去。然后发现问题在于自己最开始的做法是对点染色并不是对区间染色所以导致样例都过不去。例如[1,2] 染成1 [3,4]染成1如果是对点染色,那么点1 2 3 4都染色了输出时答案就是1 1。显然这是不对的因为我们只对区间[1,2]和区间[3,4]染色了,但是区间[2,3]并没有染色。所以正确答案应该是1 2。
- 针对上面的问题对区间缩减一点。给区间染色例如给区间a ~ b染色改为区间[a+1,b]那么就不会出现这种情况了。也就是相当于[1,3]区间有3个点但是只有2条线段。线段树正好是区间线段。利用右端点表示前面一个单位区间,比如给1 2染色实际染[2,2]这一段。那么区间[2,2]就表示1 ~ 2这一段。也就是给定的区间看做一个左开右闭(]的区间。
- 坑点就是建树要建一颗[1,8000]的满线段树不是[1,n]。然后查询的时候利用O(n)复杂度遍历一遍所有的叶节点,并且存储前一个叶节点的颜色,只要当前颜色和前面颜色不一样那么颜色次数+1。
这道题还是有点东西的,主要是不太好理解为什么左端点要+1,右端点却不用+1。理解了这个问题这道题就简单了。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define lson k<<1,l,m
#define rson k<<1|1,m+1,r
const int maxn = 8005;
int color[maxn<<2];
int ans[maxn];
int pre; //前一个叶节点的颜色
void push_down(int k)
{
if(color[k] != -1){
color[k<<1] = color[k<<1|1] = color[k];
color[k] = -1;
}
return ;
}
void update(int k,int l,int r,int ql,int qr,int ans)
{
if(qr < l || r < ql){
return ;
}
if(ql <= l && r <= qr){
color[k] = ans;
return ;
}
push_down(k);
int m = (l+r)>>1;
update(lson,ql,qr,ans);
update(rson,ql,qr,ans);
}
void query(int k,int l,int r)
{
if(l == r){
if(color[k] != pre){
ans[color[k]]++;
pre = color[k];
}
return ;
}
push_down(k);
int m = (l+r)>>1;
query(lson);
query(rson);
}
int main()
{
int n;
while(~scanf("%d",&n)){
memset(ans,0,sizeof(ans));
pre = -1;
memset(color,-1,sizeof(color));
for(int i = 0;i < n;i++){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
update(1,1,8000,x+1,y,z);
}
query(1,1,8000);
for(int i = 0;i <= 8000;i++){
if(ans[i]){
printf("%d %d\n",i,ans[i]);
}
}
printf("\n");
}
return 0;
}
愿你走出半生,归来仍是少年~