USACP section1.2 Milking Cows

把所有区间(如果能)合并起来,求最长连续区间长度和最长间隔长度(两个区间之间,如果只有一个区间为0);

/*

PROG: milk2

LANG: C++

*/



# include <cstdio>

# include <cstdlib>



# define N 5000 + 10



struct val{

    int s, t;

} a[N];



int n;



int cmp(const void *x, const void *y)

{

    val *p = (val*)x;

    val *q = (val*)y;

    if (p->s == q->s) return p->t - q->t;

    return p->s - q->s;

}



int main()

{

    freopen("milk2.in", "r", stdin);

    freopen("milk2.out", "w", stdout);



    scanf("%d", &n);

    for (int i = 0; i < n; ++i)

        scanf("%d%d", &a[i].s, &a[i].t);



    qsort(a, n, sizeof(val), cmp);



    int s = a[0].s, t = a[0].t;

    int M1 = t - s, M2 = 0;

    for (int i = 1; i < n; ++i)

    {

        if (a[i].s <= t && a[i].t > t) t = a[i].t;

        if (a[i].s > t || i == n-1)

        {

            if (t-s > M1) M1 = t - s;

            if (a[i].s-t > M2) M2 = a[i].s - t;

            s = a[i].s, t = a[i].t;

        }

    }



    printf("%d %d\n", M1, M2);



    fclose(stdin);

    fclose(stdout);



    return 0;

}

/**/

你可能感兴趣的:(IO)