活动安排问题

基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
 收藏
 关注
有若干个活动,第i个开始时间和结束时间是[Si,fi),同一个教室安排的活动之间不能交叠,求要安排所有活动,最少需要几个教室? 
Input
第一行一个正整数n (n <= 10000)代表活动的个数。
第二行到第(n + 1)行包含n个开始时间和结束时间。
开始时间严格小于结束时间,并且时间都是非负整数,小于1000000000
Output
一行包含一个整数表示最少教室的个数。
Input示例
3
1 2
3 4
2 9
Output示例
2

此问题可以看成求给定线段确定的,其中重叠线段数目的最大值。可以排序后(开始时间排序,开始时间相同结束时间小在前),从头遍历,起点数目增加,终点数目减少。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef long long LL;
using namespace std;
#define MAXN 10001
struct node
{
    LL x;
    bool s;
};
bool cmp(node a,node b)
{
    return (a.x<b.x);
}
vector<node> vv;
int main()
{
    LL t,sum=0,ans=0;
    node n1,n2;
    cin>>t;
    for(LL i=0;i<t;i++)
    {
        cin>>n1.x>>n2.x;
        n1.s = true;
        n2.s = false;
        vv.push_back(n1);
        vv.push_back(n2);
    }
    sort(vv.begin(),vv.end(),cmp);
    for(LL i=0;i<2*t;i++)
    {
        if(vv[i].s)
            sum++;
        else
            sum--;
        ans = max(sum,ans);
    }
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/joeylee97/p/6323661.html