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
题解:题目大意就是求当前的内容中有多少种颜色,每个颜色有几段,由于数据范围只有8000,所以用线段树来写,更新的时候可以不用全部都下沿。更新的复杂度是(len*logn)查询的复杂度是logn,所以总复杂度就是nlogn。用线段树写。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
const int maxn=8e3+10;
int n,wall[maxn],num[maxn];
struct node
{
int l,r,c;
}tree[maxn<<4];
vector<pii>q;
void Buildtree(int l,int r,int rt)
{ tree[rt].l=l,tree[rt].r=r;
if(l==r)
{
tree[rt].c=-1;
return ;
}
int mid=(l+r)>>1;
Buildtree(l,mid,rt<<1);
Buildtree(mid+1,r,rt<<1|1);
tree[rt].c=-1;
}
void Pushdown(int rt)
{
if(tree[rt].c==-1)return ;
tree[rt<<1].c=tree[rt<<1|1].c=tree[rt].c;
tree[rt].c=-1;
}
void Update(int L,int R,int C,int rt)
{
if(tree[rt].l==L&&tree[rt].r==R)
{
tree[rt].c=C;//该区间全部覆盖
return ;
}
Pushdown(rt);//如果有部分覆盖,那就需要把该点的颜色向下放了,因为另一种颜色来把它冲突了
int mid=(tree[rt].l+tree[rt].r)>>1;
if(R<=mid)Update(L,R,C,rt<<1);
else if(L>mid)Update(L,R,C,rt<<1|1);
else
{
Update(L,mid,C,rt<<1);
Update(mid+1,R,C,rt<<1|1);
}
}
int query(int rt,int C)
{
if(tree[rt].c!=-1&&tree[rt].l<=C&&C<=tree[rt].r)
{
return tree[rt].c;
}
if(tree[rt].l==C&&tree[rt].r==C)return tree[rt].c;
int mid=(tree[rt].l+tree[rt].r)>>1;
return C<=mid?query(rt<<1,C):query(rt<<1|1,C);
}
int main()
{
while(~scanf("%d",&n))
{ int mx=0,mxx=0;
Buildtree(0,8000,1);
memset(wall,-1,sizeof(wall));
memset(num,0,sizeof(num));
for(int i=0;i<n;i++)
{
int li,ri,co;
scanf("%d%d%d",&li,&ri,&co);
Update(li,ri-1,co,1);
mx=max(mx,ri);
}
for(int i=0;i<=mx;i++)
{
wall[i]=query(1,i);
}
for(int i=0;i<=mx;i++)
{
if(wall[i]!=wall[i+1]&&wall[i]!=-1)
{
num[wall[i]]++;
}
}
for(int i=0;i<=8000;i++)
{
if(num[i])cout<<i<<" "<<num[i]<<endl;
}
cout<<endl;
}
return 0;
}