题目链接:https://zoj.pintia.cn/problem-sets/91827364500/problems/91827365109
题意:给你n个被染了颜色的线段,后面的会覆盖前面的,输出可以看到的颜色以及这个颜色染了多少条线段。
思路:这一题和POJ2528那个贴海报那题很像,都是用的是线段树区间更新,但是这个要输出每种颜色一共染了多少条线段,所以连续的区间染上了同一种颜色只能算是一个区间。所以我们可以在query操作时加一个last表示上一个点的颜色,如果待查询的点的颜色和last相同,就不需要更新答案,就像这样
if(l==r)
{
if(sum[rt]!=-1&&sum[rt]!=last) vis[sum[rt]]++;
last=sum[rt];
return ;
}
还有就是每次输入的是[x,y],但我们要更新的确是[x+1,y]。(虽然我不知道其他的大佬是怎么看出来的)其他的就和POJ2528几乎一样啦,都是用push_down函数把染色的区间推到最底层。具体的请看代码。
代码:
#include<set>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn = 8000;
int sum[maxn<<2+7];
void push_down(int rt)
{
if(sum[rt]!=-1)
{
sum[rt<<1]=sum[rt<<1|1]=sum[rt];
sum[rt]=-1;
}
}
void update(int L,int R,int color,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
sum[rt]=color;
return ;
}
push_down(rt);
int m=(l+r)>>1;
if(L<=m) update(L,R,color,lson);
if(R>m) update(L,R,color,rson);
}
int vis[maxn+7];
int last;
void query(int L,int R,int l,int r,int rt)
{
if(l==r)
{
if(sum[rt]!=-1&&sum[rt]!=last) vis[sum[rt]]++;
last=sum[rt];
return ;
}
push_down(rt);
int m=(l+r)>>1;
if(L<=m) query(L,R,lson);
if(R>m) query(L,R,rson);
}
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(sum,-1,sizeof(sum));
for(int i=1; i<=n; i++)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
update(x+1,y,c,0,maxn,1);
}
memset(vis,0,sizeof(vis));
last=-1;
query(0,maxn,0,maxn,1);
for(int i=0; i<=maxn; i++) if(vis[i]) printf("%d %d\n",i,vis[i]);
printf("\n");
}
return 0;
}