ZOJ 1610 Count the Colors(线段覆盖着色:离散化)

来源:互联网 发布:高大上简历 知乎 编辑:程序博客网 时间:2024/06/06 23:17

ZOJ 1610 Count the Colors(线段覆盖着色:离散化)

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1610

题意:

       给你n条[0,8000]范围内的带不同颜色的线段,问你最终该线段都有哪些颜色,且这些颜色分别出现了多少次(即在多少段线段内出现了)?

分析:

       本题可以用线段树做,不过离散化更简单且易理解.然后本题与之前做的ZOJ 2747本质上一样:

http://blog.csdn.net/u013480600/article/details/39479819

       首先我们读入每段线段,然后把所有的不同x坐标保存下来,然后对x坐标排序去重,之后的x数组大小-1就是整个有效区间被线段分成了多少子段.每个子段的颜色都只与最后一个在这个线段上着色的原始线段有关.

       然后我们扫描每一个子段即可记录每种颜色各出现了多少次.

       注意:如果连续几个子段出现了相同颜色,只能算该颜色出现1.

AC代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=8000*2+5;int n;      //原始线段数目int x[maxn];//不同的x坐标int num1;   //x坐标数目struct Node{    int x1,x2,c;}nodes[maxn];int main(){    while(scanf("%d",&n)==1)    {        num1=0;        for(int i=0;i<n;++i)        {            scanf("%d%d%d",&nodes[i].x1,&nodes[i].x2,&nodes[i].c);            x[num1++]=nodes[i].x1;            x[num1++]=nodes[i].x2;        }        sort(x,x+num1);        num1=unique(x,x+num1)-x;        int color[maxn];//color[i]表示x[i]到x[i+1]线段的颜色        for(int i=0;i<num1;++i) color[i]=-1;//初始化,-1代表无颜色        for(int i=0;i<n;++i)        {            int L_x=lower_bound(x,x+num1,nodes[i].x1)-x;            int R_x=lower_bound(x,x+num1,nodes[i].x2)-x;            for(int j=L_x;j<R_x;++j) color[j]=nodes[i].c;//着色        }        int ans[maxn];//ans[i]==x表第i种颜色出现了x次        memset(ans,0,sizeof(ans));        for(int i=0;i<num1;++i)        {            if(color[i]>=0&&color[i]!=color[i+1]) ++ans[color[i]];        }        for(int i=0;i<=8000;++i)if(ans[i])            printf("%d %d\n",i,ans[i]);        printf("\n");    }    return 0;}

0 0