調度問題-完成事件需要時間:a[i],截止時間:t[i]

問題一:https://nanti.jisuanke.com/t/43373

水災了。有n個城市。搶救每個城市需要時間a[i]。每個城市會在t[i]時被銷燬。
必須在<=t[i](小於等於)才能搶救這個城市。問你最多能夠搶救多少城市,時間從0開始。
in:
5
5 10
6 15
2 7
3 3
4 11
out:
4

在這裏插入圖片描述

#include <bits/stdc++.h>
#define LL long long
using namespace std;

struct node{
    LL t, h;
}a[200005];
struct rule{
    int operator()(const node &a, const node &b){
        return a.t<b.t;
    }
};
priority_queue<node, vector<node>, rule> q;
int main(){
    LL n; scanf("%lld", &n);
    for(LL i=1; i<=n; i++){
        scanf("%lld%lld", &a[i].t, &a[i].h);
    }
    sort(a+1, a+n+1, [](node &a, node &b){return a.h<b.h;});
    LL H=0, ans=0;
    for(LL i=1; i<=n; i++){
        if(H+a[i].t<=a[i].h){
            ans++;
            H+=a[i].t;
            q.push(a[i]);
        }
        else if(!q.empty()){
            node t=q.top();
            if(t.t>a[i].t&&H-t.t+a[i].t<=a[i].h){
                q.pop();
                q.push(a[i]);
                H=H-t.t+a[i].t;
            }
        }
    }
    printf("%lld\n", ans);

    return 0;
}

問題二:https://codeforces.com/contest/864/problem/E

起火了。有n個文件。搶救每個文件需要時間a[i]。每個文件會在t[i]時被銷燬,有價值c[i]。
必須在<t[i](嚴格小於)才能搶救這個文件。問你最多能夠搶救多少價值的文件,時間從0開始。

t[i]f[i][j]ij我們還是按t[i]排序。用f[i][j]:前i個文件在時間j以內最多能夠搶救最大價值。

#include <bits/stdc++.h>
#define LL long long
using namespace std;

struct node{
    int t, d, p, i;
}a[105];

int f[105][2005];//前i個文件。時間恰好是j能保存的最多價值
int g[105][2005];
int main(){

    int n; scanf("%d", &n);
    for(int i=1; i<=n; i++){
        scanf("%d%d%d", &a[i].t, &a[i].d, &a[i].p);
        a[i].i=i;
    }
    sort(a+1, a+n+1, [](node &a, node &b){return a.d<b.d;});
    int ans=0, s=0;
    for(int i=1; i<=n; i++){
        for(int j=0; j<=2000; j++){
            if(j-a[i].t>=0&&j<a[i].d){
                if(f[i-1][j]>f[i-1][j-a[i].t]+a[i].p){
                    f[i][j]=f[i-1][j];
                    g[i][j]=0;
                }
                else{
                    f[i][j]=f[i-1][j-a[i].t]+a[i].p;
                    g[i][j]=1;
                }

            }
            else{
                f[i][j]=f[i-1][j];
                g[i][j]=0;
            }
            if(f[i][j]>ans){
                ans=f[i][j];
                s=j;
            }
        }
    }
    cout<<ans<<endl;
    vector<int> v;
    while(n>=1){
        if(g[n][s]){
            v.push_back(a[n].i);
            s-=a[n].t;
        }
        n--;
    }

    cout<<v.size()<<endl;
    for(int i=v.size()-1; i>=0; i--){
        cout<<v[i]<<" ";
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章