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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章