您的位置:首页 > 其它

UVA10020用最少的线段去覆盖给定的线段

2016-03-13 22:29 302 查看
这题是个贪心,先把每条线段按照左端点进行排序,然后贪心,怎么贪呢,

每次都找到最长的线段,记录下坐标,(如果某个坐标为负值,初始的为负值,即表示下面有一段断掉了,直接return 0)更新起点值,具体的看代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<string>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cctype>
#include<queue>
#define LL long long
using namespace std;
const int maxn=1e5+10;
const double eps=1e-8;
const int Max=2147483647;
struct line
{
double a,b;
}lin[maxn];
int m;
int l;
int t[maxn];
int re;
int cmp(line x,line y)
{
if(x.a==y.a)
return x.b<y.b;
return x.a<y.a;
}
int solve()
{
double t1=0;
int tem=0;
while(t1<m)
{
int  tt=-1;
double ma=0;
for(;tem<l;tem++)
{
if(lin[tem].a<=t1)
{
if(lin[tem].b-t1>ma)
{
ma=lin[tem].b-t1;
tt=tem;
}
}
else
break;
}
if(tt<0)
return 0;
t1=lin[tt].b;
t[re++]=tt;
}
return re;
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>m;
l=0;
while(scanf("%lf%lf",&lin[l].a,&lin[l].b))
{
if(lin[l].a==0&&lin[l].b==0)
break;
l++;
}
re=0;
//  for(int i=0;i<l;i++)
//     cout<<lin[i].a<<' '<<lin[i].b<<endl;
sort(lin,lin+l,cmp);
int ans=solve();
if(!ans)
cout<<0<<endl;
else
{
cout<<ans<<endl;
for(int i=0;i<ans;i++)
cout<<lin[t[i]].a<<' '<<lin[t[i]].b<<endl;
}
if(T)
cout<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: