您的位置:首页 > 其它

UVA10020->贪心

2016-07-26 01:27 302 查看
题意:给一些区间,求能把[0,M]所有点覆盖需要的最少区间个数,并输出这些区间的左右端点

题解:贪心,关键在于贪心策略能不能想对。

       贪心策略:把所有可能有用的区间按照左端点递增的顺序排序,然后依次去找能够缩小区间右边界范围的区间,直到区间的左端点也被覆盖,这里枚举的复杂度为O(N^2),

这样的贪心策略就能保证每次选取的区间都是最优的解

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std ;
#define MAX 100005
int visit[MAX] ;
struct Node
{
int l , r ;
}len[MAX] ;
Node out[MAX] ;
bool comp(const struct Node &x , const struct Node &y)
{
return x. l < y.l ;
}
int main()
{
int T ,M;
scanf("%d" , &T) ;
while(T --)
{
scanf("%d" , &M) ;
int LL = 0 , RR = M ;
int n ;
int pos = 0 ;
int i= 0 ;
while(1)
{
scanf("%d%d", &len[i].l , &len[i].r) ;
if(len[i].r<0 || len[i].l>M) continue ;
if(len[i].l==0&&len[i].r==0)
{
n = i ;
break ;
}
i ++ ;
}
sort(len , len + n ,comp) ;
int ans = 0;
memset(visit , 0 , sizeof(visit)) ;
int judge = 0 ;
for (i = 0; i < n ; ++i)
{
//cout << len[i].l << ' ' << len[i].r << ' ' << len[i].length<<endl;
if(len[i].r >= RR && len[i].l < RR && !visit[i])
{
ans ++ ;
out[pos] = len[i] ;
pos ++ ;
if(len[i].l <= LL)
{
judge = 1;
break ;
}
RR = len[i].l ;
visit[i] = 1;
i = -1 ;
}
}
if(judge)
{
cout << ans <<endl;
for(i = pos - 1 ; i >= 0 ;i --)
{
cout<<out[i].l<<' '<< out[i].r << endl ;
}
}
else cout <<'0'<<endl ;
if(T>0) cout << endl ;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: