POJ 3186 Treats for the Cows(贪心)

来源:互联网 发布:网络医生兼职 编辑:程序博客网 时间:2024/06/15 16:52

this is the question’s link

I believe this question is a greedy algorithm ,so I sort the data first and than update the maximum vale of right value of each member of struct node

#include <iostream>#include <cstring>#include <algorithm>#define ll long long#define maxn 105using namespace std;struct node{    int left,right;}cow[25005];int cmp(node a,node b){    return a.left < b.left;}int main(){    int m,n;    cin>>m>>n;    for(int i=1;i<=m;i++)    {        cin>>cow[i].left>>cow[i].right;    }    sort(cow+1,cow+m+1,cmp);    int l = 0,i=0;    int ans=0;    while(l < n)    {        int r1 = -1,r2;        while(cow[++i].left<=l+1)        {            r1 = cow[i].right >r1 ?cow[r2 = i].right:r1;        }        if(r1==-1)        {            cout<<-1;            return 0;        }        ans++;        i--;        l=r1;    }    cout<<ans;    return 0;}