区间问题(贪心)

区间调度问题

有n项工作,每项工作分别在si时间开始,ti结束。对于每项工作你都可以选择参加与否。但是如果参加了就一定要全程参与。 此外,参加工作的时间段不能重叠。你的目标是参与尽可能多的工作?

思路:按照每项工作的结束时间从小到大排序,每次选择最小的,就是最优解。。。为什么呢?  因为每次选择一个结束时间最早的,对后面其它影响最小

看代码

#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9+7;
const int maxn=1e5+10;
const int maxk=1e4+10;
const int maxx=1e4+10;
const ll maxe=1000+10;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
int n;
struct work
{
    int be,en;
}w[maxn];
bool cmp(const work a,const work b)
{
    return a.en<b.en;
}
void solve()
{
    int t=0,ans=0;
    for(int i=0;i<n;i++)
    {
        if(t<=w[i].be)
        {
            ans++;
            t=w[i].en;
        }
    }
    cout<<ans<<endl;
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>w[i].be>>w[i].en;
    }
    sort(w,w+n,cmp);
    solve();
    return 0;
}
当初的梦想实现了吗,事到如今只好放弃吗~
原文地址:https://www.cnblogs.com/caijiaming/p/9413508.html