Computer Arrangement [经典贪心]

原题:http://oj.acm.zstu.edu.cn/JudgeOnline/problem.php?id=2514

Description
每年新学期,计算中心的老师都要安排上机时间。 现设有n个班级E={1, 2, 3, ..., n}, 要使用8号机房,同一时间内只允许一个班级使用该机房。设班级i上机的起止时间区间为[si,fi),如果班级i使用了8号机房, 则它在时间[si,fi)内占用该机房,若区间[si,fi)和[sj,fj)不相交,则称班级i和j均可安排上机的。现在要求你安排一下上机情况,使尽可能多的班级能有机会上机。
Input
有多组测试数据。 第1行先输入整数t(1<= t <= 100),表示共有t组测试数据。 每组测试数据输入共有3行, 第1行为一个整数n(1 <= n <= 2000) 表示班级数 第2行共n个整数,为这n个班级希望上机的开始时间(以某一时间为基准) 第3行共n个整数,为这n个班级上机的终止时间
Output
对于每个测试案例输出最多可以安排上机的班级
Sample Input
1
11
1 3 0 5 3 5 6 8 8 2 12
4 5 6 7 8 9 10 11 12 13 14
Sample Output
4

题解:说是贪心了,所以我们要尽可能多地安排.当安排了第I个班时,如果结束的越早的话,那么就有更多的时间来安排其他班级,贪的就是尽可能多的剩出时间.
#include <bits/stdc++.h>
const int N=2000+5;
using namespace std;
struct arr{
    int l,r;
}a[N];
bool comp(arr a,arr b){
    return a.r<b.r;
}
int main(){
    int t,n;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++) scanf("%d",&a[i].l);
        for(int i=1;i<=n;i++) scanf("%d",&a[i].r);
        sort(a+1,a+1+n,comp);
        int ans=0,end=0;
        for(int i=1;i<=n;i++){
            if(a[i].l>=end) end=a[i].r,ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}
/**************************************************************
    Problem: 2514
    User: 2018330300029
    Language: C++
    Result: Accepted
    Time:56 ms
    Memory:1484 kb
****************************************************************/

猜你喜欢

转载自www.cnblogs.com/-yjun/p/10507975.html