poj 百练 Intervals 区间覆盖

算法的思想:首先对于所有的节点根据起始坐标按照从小到大进行排序。定义两个变量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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值