您的位置:首页 > 其它

poj 百练 Intervals 区间覆盖

2013-02-15 19:41 316 查看
算法的思想:首先对于所有的节点根据起始坐标按照从小到大进行排序。定义两个变量from和to,分别记录前一个区间的起始坐标和停止坐标。然后看下一个节点:(from1,to1)

case 1:if(from1>=to) then 合并

from不变;to修改为to和to1中的较大者。

case 2:if(from1<to)then print the interval

and update the from and to

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

struct Node{
int from;
int to;
};

struct Node nodes[50005];
int cmp(const void * a,const void *b){
struct Node aa,bb;
aa=*((struct Node*)a);
bb=*((struct Node*)b);
return aa.from-bb.from;
}
int valid[50005];
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
int f,t;
scanf("%d %d",&f,&t);
nodes[i].from=f;
nodes[i].to=t;
}

qsort(nodes,n,sizeof(Node),cmp);

int from=nodes[0].from;
int to=nodes[0].to;
for(int j=1;j<n;j++){
if(to>=nodes[j].from){
valid[j-1]=0;
nodes[j].from=from;
to=nodes[j].to>to?nodes[j].to:to;
}
if(to<nodes[j].from){
cout<<from<<" "<<to<<endl;
from=nodes[j].from;
to=nodes[j].to;
}
}
cout<<from<<" "<<to<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: