【Minimal coverage】【UVA - 10020】(區間排序,cmp)
題目:
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的和左端點大於m的,然後看看是否有左端點小於0的或者右端點大於m的,如果有的話就可以繼續尋找,按照x的第一升序,y的第二升序排列,看看有無這種線段,有的話,按照y的升序排列,之後存放到數組裡,更新最右端點。依次進行,最後能夠實現全部的線段查詢完畢。
ac程式碼:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn =1e6+100;
struct node{
int x,y;
}pot[maxn];
bool cmp(node a,node b)
{
if(a.x==b.x)
return a.y<b.y;
else
return a.x<b.x;
}
bool cmp1(node a,node b)
{
return a.y<b.y;
}
int num[maxn*2];
int main()
{
int t,m,i;
cin>>t;
while(t--)
{
int cnt=0;
int flagx=0,flagy=0;
int mcnt=0;
scanf("%d",&m);
for(cnt=0;;cnt++)
{
scanf("%d%d",&pot[cnt].x,&pot[cnt].y);
if(!pot[cnt].x&&!pot[cnt].y)
break;
if(pot[cnt].y<=0||pot[cnt].x>=m)
cnt--;
else
{
if(pot[cnt].x<=0)
flagx=1;
if(pot[cnt].y>=m)
flagy=1;
}
}
int l=0,fi=0;
if(flagx&&flagy&&cnt==1)
printf("1\n%d %d\n",pot[0].x,pot[0].y);
else if(flagx&&flagy)
{
sort(pot,pot+cnt,cmp);
int ff=0;
while(l<m)
{
for(i=fi;i<cnt;i++)
{
if(pot[i].x>l&&i>0&&pot[i-1].y<pot[i].x)
{
ff=1;
printf("0\n");
break;
}
else if(pot[i].x>l)
break;
}
sort(pot+fi,pot+i,cmp1);
num[++mcnt]=pot[i-1].x;
num[++mcnt]=pot[i-1].y;
l=pot[i-1].y;
fi=i;
if(ff)
break;
}
if(ff)
{
puts("");
continue;
}
printf("%d\n",mcnt/2);
for(i=1;i<=mcnt;i+=2)
{
printf("%d %d\n",num[i],num[i+1]);
}
}
else
{
printf("0\n");
}
if(t)
puts("");
}
}