uva 10020 Minimal coverage

题意:给你N条线段(Li,Ri)映射到x轴上,然后让你用其中的几条线段(条数最少)覆盖【0,M】

方法:利用贪心思想。对线段按照长度进行排序,在这里可以在输入的时候,对线段进行选择,如果Ri<0||Li>M这直接删除。然后每次在选择线段的时候,尽可能的选择长的,这里用到了贪心思想

#include <cstdio>
#include <iostream>
#include <sstream>

using namespace std;

struct NODE
{
    int x,y;
};
NODE node1[100010],node2[100010];
int main()
{
    int m;
    int p =0;
    // int L[50005],R[50005];
    //char a[250];

    scanf("%d",&m);
    for(; p < m; p++)
    {
        if(p != 0)
            printf("\n");
        int n,l,r;
       // int temp = 0;
        int p1 = 0;
        int p2 = 0;
        scanf("%d",&n);

        while(scanf("%d %d",&l,&r)&&(l || r))
        {
            if(r > 0)
            {
                p1 ++;
                node1[p1].x = l;
                node1[p1].y = r;
            }
        }
        int Min =0,Max =0;
        int flag =0;
        int index;
        while(1)
        {

            if(Min >= n) break;
            Max = 0;
            flag = 0;
            for(int i = 1; i<=p1;i++)
            {
                if(Min >= node1[i].x && Max < node1[i].y)
                {
                    index = i;

                    flag = 1;
                    Max = node1[i].y;
                }
            }
            if(flag)
            {
                ++p2;
                node2[p2] = node1[index];
                Min = node1[index].y;    //对左边贪心
              //  printf("node2x --- %d\nnode2y ----- %d\n",node1[index].x,node1[index].y);
            }
            else
                break;
        }
        if(flag)
        {
            printf("%d\n",p2);
            for(int i = 1; i <= p2; i++)
                printf("%d %d\n",node2[i].x,node2[i].y);
        }
        else
            printf("0\n");

    }
    return 0;
}


你可能感兴趣的:(uva 10020 Minimal coverage)