【问题描述】
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].
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.
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
【解题思路】
选取覆盖线段的度量标准:所有左端点被覆盖线段中找右端点最远的线段。
输入的时候处理一下,左端点大于输入值M的丢掉,右端点小于0的丢掉,然后排序,然后从最长的开始找,拼接起来。
【具体实现】此处借鉴别人的代码
#include<iostream> #include<algorithm> #include<cstdio> #include<string.h> using namespace std; int M; struct node { int x1,x2; } Node[100100],an[100100]; int cmp(node a,node b) { return a.x1<b.x1; } int main() { int T; int M; int a,b; int ans=0; scanf("%d",&T); int m=T; while(T--) { ans=0; memset(Node,0,sizeof(Node)); memset(an,0,sizeof(an)); scanf("%d",&M); for(int i=0;; i++) { scanf("%d%d",&a,&b); if(a==0&&b==0) break; if(a>M||b<0) continue; Node[ans].x1=a; Node[ans].x2=b; ++ans; } if(ans==0) { printf("0\n"); } else { int min=0,max=0; int step=0,pox; int f=0; sort(Node,Node+ans,cmp); while(1) { if(min>=M) break; max=0; f=0; for(int i=0; i<ans; i++)//贪心算法 只看左边的数据就行了 { if(min>=Node[i].x1&&max<Node[i].x2)//左边的值一定大于Node[i].x1才能完成覆盖,右边的值一定小与Node[i].x2才能是有效值 { pox=i; f=1; max=Node[i].x2; } } if(f) { an[step++]=Node[pox]; min=Node[pox].x2;//对左边贪心 } else break; } if(f) { printf("%d\n",step); for(int i=0; i<step; i++) printf("%d %d\n",an[i].x1,an[i].x2); } else printf("0\n"); } if(T>0) printf("\n"); } return 0; }
【额外补充】
题目意思理解清楚就好了。