您的位置:首页 > 其它

[贪心]uva10020 Minimal coverage

2014-03-12 20:58 323 查看


 Minimal coverage 

The Problem

Given several segments of line (int the X axis) with coordinates [Li,Ri]. You are to choose the minimal amount of them, such they would completely cover the segment [0,M].

The Input

The first line is the number of test cases, followed by a blank line.
Each test case in the input should contains an integer M(1<=M<=5000), followed by pairs "Li Ri"(|Li|, |Ri|<=50000, i<=100000), each on a separate line. Each test case
of input is terminated by pair "0 0".
Each test case will be separated by a single line.

The Output

For each test case, in the first line of output your programm should print the minimal number of line segments which can cover segment [0,M]. In the following lines, the coordinates of segments, sorted by their
left end (Li), should be printed in the same format as in the input. Pair "0 0" should not be printed. If [0,M] can not be covered by given line segments, your programm should print "0"(without quotes).
Print a blank line between the outputs for two consecutive test cases.

Sample Input

2

1
-1 0
-5 -3
2 5
0 0

1
-1 0
0 1
0 0


Sample Output

0

1
0 1


Alex Gevak

September 10, 2000 (Revised 2-10-00, Antonio Sanchez)

题意:给出一个数字M,再给出一些区间,求出使用最少的区间使这些区间覆盖0-M。

思路:典型的贪心题目,首先预处理,把和所给的范围不相关的区间过滤掉。再在这些区间中选择使右边的区间能到达最远的范围。

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

class Node
{
public:
int x,y;
}node[100005];

vector<Node> st;

bool cmp(Node r,Node t)
{
return r.x<t.x;
}

int main()
{
int n;
cin>>n;
while(n--)
{
int m,num=0;
st.clear();
cin>>m;
int left,right;
while(cin>>left>>right&&(left!=0||right!=0))
{
if(left<m&&right>0)
{
node[num].x=left;
node[num++].y=right;
}
}
sort(node,node+num,cmp);
int start=0,tag=1,tag1;
int i,j,k,maxlen;
while(start<m)
{
maxlen=start,tag1=0;
for(i=0;i<num;i++)
{
if(node[i].y>maxlen&&node[i].x<=start) maxlen=node[i].y,k=i,tag1=1;
else if(node[i].x>start) break;
}
if(tag1==0)
{
tag=0;
break;
}
start=node[k].y;
st.push_back(node[k]);
}
if(tag==0) cout<<"0"<<endl;
else
{
cout<<st.size()<<endl;
for(i=0;i<st.size();i++)
cout<<st[i].x<<" "<<st[i].y<<endl;
}
if(n!=1) cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心