Ural 1303 minimal coverage (Greedy)

Source: Internet
Author: User

Subject address: Ural 1303

First, sort by the Left endpoint of each line segment, and then set a start point S. Each time, the largest right endpoint is found from the line segment whose start point is less than or equal to S. And use the right endpoint as the new starting point S. Scan it from left to right.

The Code is as follows:

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;#define LL __int64const int INF=0x3f3f3f3f;int a[100000];struct node{    int l, r, ll, rr;} fei[100000];int cmp(node x, node y){    return x.l<y.l;}int main(){    int m, i, j, n, l, r, s, max1, cnt=0, tot, pos, flag, flag1, ll, rr;    scanf("%d",&m);    while(scanf("%d%d",&ll, &rr)!=EOF&&(ll||rr))    {        if(rr<=0||ll>=m) continue ;        fei[cnt].ll=ll;        fei[cnt].rr=rr;        l=ll;r=rr;        if(l<0)            l=0;        if(r>m)            r=m;        fei[cnt].l=l;        fei[cnt++].r=r;    }    sort(fei,fei+cnt,cmp);    s=0;    tot=0;    if(cnt==0)    {        printf("No solution\n");    }    else    {        for(i=0; i<cnt;)        {            max1=-1;            flag=0;            while(fei[i].l<=s&&i<cnt)            {                flag=1;                if(max1<fei[i].r)                {                    max1=fei[i].r;                    pos=i;                }                i++;            }            if(!flag)                break;            if(s<max1)            {                a[tot++]=pos;                s=max1;            }        }        if(i<cnt||s<m)            puts("No solution");        else        {            printf("%d\n",tot);            for(i=0; i<tot; i++)            {                printf("%d %d\n",fei[a[i]].ll,fei[a[i]].rr);            }        }    }    return 0;}


Ural 1303 minimal coverage (Greedy)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.