题目地址:点击打开链接
题意:
在一条长度为8000的线段上染色,每次把区间[a,b]染成c颜色。显然,后面染上去的颜色会覆盖掉之前的颜色。求染完之后,每个颜色在线段上有多少个间断的区间。
思路:
区间问题用线段树,成段的延迟更新区间,最后把所有的区间下压到叶子结点,统计叶子结点的颜色。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 8e3+5;
int col[maxn*4], vis[maxn*4], ans[maxn*4], n;
void pushdown(int root)
{
if(col[root] != -1)
{
col[root*2] = col[root*2+1] = col[root];
col[root] = -1;
}
}
void update(int root, int l, int r, int i, int j, int val)
{
if(i <= l && j >= r)
{
col[root] = val;
return ;
}
if(col[root] == val) return ;
pushdown(root);
int mid = (l+r)/2;
if(mid >= i) update(root*2, l, mid, i, j, val);
if(mid < j) update(root*2+1, mid+1, r, i, j, val);
}
void query(int root, int l, int r)
{
// cout << root << endl;
if(col[root] >= 0)
{
for(int i = l; i <= r; i++)
vis[i] = col[root];
return ;
}
if(l != r && col[root] == -1)
{
int mid = (l+r)/2;
query(root*2, l, mid);
query(root*2+1, mid+1, r);
}
}
int main(void)
{
while(cin >> n)
{
memset(col, -1, sizeof(col));
for(int i = 1; i <= n; i++)
{
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
update(1, 1, 8000, x+1, y, z);
}
memset(vis, -1, sizeof(vis));
memset(ans, 0, sizeof(ans));
query(1, 1, 8000);
int i = 1;
while(i < maxn)
{
int color = vis[i], j = i+1;
if(color == -1) { i++; continue; }
while(vis[j] == color&& j < maxn) j++;
ans[color]++;
i = j;
}
for(int i = 0; i < maxn; i++)
if(ans[i])
printf("%d %d\n", i, ans[i]);
printf("\n");
}
return 0;
}
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