uva 10020

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
题意:
有n个闭区间[Li,Ri],给你一个整数,要你求出最少区间覆盖[Li,Ri].
思路:
参考算法竞赛与入门经典(紫书)P233,首先进行预处理,在区间[Li,Ri]外面的首先要去掉,预处理完成后在相互包含的情况下,小区间显然不能考虑。再把各个区间按照
Li从小排到大,如果li>0肯定就是无解,如果Li<=0进行搜索,让Ri尽可能的大。
代码:
#include<cstdio>
#include<algorithm>
int L[50001][2];
using namespace std;
int T,M;
int f,n;
int pos,maxn,sum,posmax;
struct node
{
    int l;
    int r;
};
node arr[100001],brr[100001];
bool cmp(node a,node b)
{
    return a.l<b.l;
}
void solve()
{
    sort(arr,arr+n,cmp);
    if(arr[0].l>0)
        printf("0\n");
    else
    {
        pos=0;maxn=0;sum=1;
        while(pos+1<n&&arr[pos+1].l<=0)
        {
            pos++;
            if(arr[pos].r>arr[maxn].r)
                maxn=pos;

        }
        pos=maxn; brr[1].l=arr[pos].l;brr[1].r=arr[pos].r;
        while(pos<n&&brr[sum].r<=M)
        {
            f=1;
            posmax=maxn;
            while(pos+1<n&&arr[pos+1].l<=arr[maxn].r)
            {
                f=0;
                pos++;
                if(arr[pos].r>arr[posmax].r) posmax=pos;
            }
            if(f)   break;
            maxn=posmax;
            sum++;
            brr[sum].l=arr[maxn].l;
            brr[sum].r=arr[maxn].r;
        }
        if(brr[sum].r>=M)
        {
            printf("%d\n",sum);
            for(int i=1;i<=sum;i++)
                printf("%d %d\n",brr[i].l,brr[i].r);

        }
        else printf("0\n");
    }

}
void init()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&M);
         n=0;
        while(scanf("%d%d",&arr[n].l,&arr[n].r))
        {
            if(arr[n].l==0&&arr[n].r==0)
                break;
                n++;
        }
        solve();
    }
}
int main()
{

    init();
   // solve();
    return 0;
}


发布了76 篇原创文章 · 获赞 7 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章