[Greedy] segments covered

Original title Portal

Thinking


This question is the second chapter of the Conference on "Fun learning algorithm", the start time of the meeting endpoint line is equal to the end time.
Select the meeting of greedy strategy is to: select the first scheduled meeting ends and the compatibility of the meeting after ordering.
Ordering principle is: If both ends of the case by the start time in descending order, if the end of the same time, press the end time in ascending order.
But in this question there is a problem with the meeting point difference is that it directly descending order by the end of the time on it, without having to engage in two conditions.
This question also has a pit, that is: not necessarily to enter the segment of the left point !!! right point output will first, if not the default judgment about it, will be cut in half pit of points! ! ! Also, this question will be negative! ! ! So the earliest end time default value can not be zero, or at least -999.

Code


#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
using namespace std;

int ans,n,i,last=-9999;
struct xd{int beg;int end;};
xd xds[101];
bool cmp(xd a,xd b)
{
    /*if(a.end==b.end)
        return a.beg>b.beg;*/
    return a.end<b.end;
}

int main()
{
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cin>>xds[i].beg>>xds[i].end;
        if(xds[i].beg>xds[i].end)
            swap(xds[i].beg,xds[i].end);
    }   
    sort(xds+1,xds+1+n,cmp);
    for(i=1;i<=n;i++)
    {
        if(xds[i].beg>=last)
            last=xds[i].end,ans++;
    }
    cout<<ans;
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongdakai/p/11290930.html