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

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值