UVA - 10020 Minimal coverage(最小覆盖)

题目链接:
UVA - 10020 Minimal coverage
思路:
按左端点升序,每次遍历固定左端点,更新右端点;
在一轮遍历完成后,更新左端点的值,如果左端点大于题目设定的右端点则退出。
特殊情况:如果排序之后第一个区间的左端点大于目标区间的左端点,则直接退出,因为后面区间的左端点更是大于目标区间的左端点。

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
struct node{
	int l,r;
}num[100010];
vector<node> v;
bool cmp(const node &a,const node &b){
	return a.l<b.l;
}
int main(int argc, char** argv) {
	int Case;
	scanf("%d",&Case);
	getchar();//换行 
	getchar();//空行 
	while(Case--){
		v.clear();
		int s=0,t,cnt=0;
		scanf("%d",&t);
		int x,y;
		while(scanf("%d %d",&x,&y)!=EOF){
			if(x==0&&y==0) break;
			num[cnt].l=x;
			num[cnt].r=y;
			cnt++;
		}
		sort(num,num+cnt,cmp);
		if(num[0].l>s){
			printf("0\n");
		}else{
			int ind=0,flag=0;
			while(s<t){ 
				int idx=-1,right=s;
				for(int i=0;i<cnt;i++){
					if(num[i].l<=s&&num[i].r>right){//固定左端点,更新右端点
						right=num[i].r;
						idx=i;
					}
				}
				if(right!=s){
					node num_tmp;
					num_tmp.l=num[idx].l;num_tmp.r=num[idx].r;
					v.push_back(num_tmp);
					s=right;
				}else{
					printf("0\n");
					flag=1;
					break;
				}
			}
			if(!flag){
				printf("%d\n",v.size());
				for(int i=0;i<v.size();i++){
					printf("%d %d\n",v[i].l,v[i].r);
				}
			}
		}
		if(Case) printf("\n");
	}
	return 0;
}

参考自:
https://blog.csdn.net/wss_ang/article/details/77513382

猜你喜欢

转载自blog.csdn.net/zhuixun_/article/details/84404485
今日推荐