POJ - 2620Minimal coverage

问题描述:

Given set of line segments [Li , Ri] with integer coordinates of their end points. Your task is to find the minimal subset of the given set which covers segment [0,M] completely (M is a positive integer).

输入说明:

First line of the input contains number M (1 <= M <= 5000). Subsequent lines of input contain pairs of numbers Li and Ri (abs(Li), abs(Ri) <= 50000). Each pair is placed on separate line. Numbers in the pair are separated with space(s). List of pairs is ended with pair of integers “0 0”. i <= 100000

输出说明:

Your program should print in the first line of output the power of minimal subset of segments which covers segment [0, M]. The list of segments of covering subset must follow. Format of the list must be the same as described in input with exception that ending pair “0 0” should not be printed. Segments should be printed in increasing order of their left end point coordinate.

If there is no covering subset then print “No solution” to output.

SAMPLE INPUT:

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

SAMPLEOUTPUT:

No solution

HINTS:

Huge input,scanf is recommended.
Sample input #2
1
-1 0
0 1
0 0

Sample output #2
1
0 1

思路:

题目的意思就是告诉我们一些棍子,问我们能不能用这些棍子覆盖一个区间(0~m),如果可以就输出所需要的的最小的木棍说,如果不可以就输出“NO solution”。解法就是找到定义一个start,每次都去找左端点小于start,右端点最大的的木棍,然后更新start为木棍的右端,重复操作,直到全部覆盖区间,或者有部分区间无法被覆盖。

AC代码:

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int l, r;
} a[100001];

bool cmp(node a,node b)//手动写一个结构体的排序
{
    return a.l < b.l;
}
int main()
{
    int m,c[100001];
    while(scanf("%d",&m)!=EOF)
    {
        memset(c,0,sizeof(c));
        int x,y,k=0,cont=0,num=0,p=0,flag=0,ans=0,i;
        while(scanf("%d%d",&x,&y)&&!(x==0&&y==0))//一开始我这里用了cin,然后超时了,建议用scanf吧,或者解绑
        {
            a[k].l=x;
            a[k++].r=y;
        }
        sort(a,a+k,cmp);//将所有的木棍按照最左端进行排序
        for(i=0; ;i++)
        {
            if(cont>=m)
            {
                break;
            }
            int ending=0,temp=0;
            while(num<k&&a[num].l<=cont)
            {
                if(a[num].r>ending)
                {
                    ending=a[num].r;
                    temp=num;
                }
                num++;
            }
            if(ending==0)
            {
                flag=1;
                break;
            }
            cont=ending;
            c[temp]=1;
            ans++;
        }
        if(flag)
        {
            cout<<"No solution"<<endl;

        }
        else
        {
            cout<<ans<<endl;
            for(i=0;i<k;i++)
            {
                if(c[i])
                {
                    cout<<a[i].l<<' '<<a[i].r<<endl;
                }
            }
            cout<<endl;
        }
    }
    return 0;
}




猜你喜欢

转载自blog.csdn.net/m0_51727949/article/details/114939465
今日推荐