求区间并的个数

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;


struct node
{
    int s,e;
};

int cmp(void const *a,void const *b)
{
    node *na ,*nb;
    na = (node *)a;
    nb = (node *)b;
    if(na->s < nb->s) return -1;
    else if(na->s > nb->s ) return 1;
    else return na->e-nb->e;
}


int main()
{
    node a[100];


    int n;
    while(scanf("%d",&n) == 1)
    {
        for(int i=0 ; i<n ; i++)
        {
            int s,e;
            scanf("%d%d",&s,&e);
            a[i].s = s;
            a[i].e = e;
        }

        qsort(a,n,sizeof(node),cmp);
        /*
        for(int i=0 ; i<n ; i++)
        {
            printf("%d %d\n",a[i].s,a[i].e);
        }
        */

        int k = 0;
        int res = 1;
        int ns = a[k].s;
        int ne = a[k].e;
        k++;
        while(k<n)
        {
            if(a[k].s>= ns && a[k].s<=ne)
            {
                if(a[k].e>ne)ne = a[k].e;
            }
            else
            {
                res++;
                ns = a[k].s;
                ne = a[k].e;
            }
            k++;
        }

        printf("%d\n",res);

    }


    return 0;
}

点赞