ACM CSP竞赛笔记(十六)——贪心算法

参考课程是我高中信息竞赛邱老师的课程。

【15-贪心】 https://www.bilibili.com/video/BV1Ft421H7YL/?share_source=copy_web\&vd_source=2c56c6a2645587b49d62e5b12b253dca

【15-贪心习题解答】 https://www.bilibili.com/video/BV1FD421s7a3/?share_source=copy_web\&vd_source=2c56c6a2645587b49d62e5b12b253dca

需要完整ACM CSP板子的可以去资源找,我设置的0积分,如果还要收费来B站私我!

贪心------只适用于单一的 可切割 的部分背包问题

练习 P2240

https://www.luogu.com.cn/problem/P2240

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int N,T;
struct Gold{
    int m,v;
    double p;
};


bool cmp(Gold &a,Gold &b){
    return a.p>b.p;
}
int main(){
    cin>>N>>T;
    vector<Gold> G(N);
    for(int i=0;i<N;i++){
        cin>>G[i].m>>G[i].v;
        G[i].p=(double)G[i].v/G[i].m;
    }
    sort(G.begin(),G.end(),cmp);
    double curm=0;
    double curv=0;
    for(int i=0;i<N;i++){
        if(G[i].m+curm<=T){//如果全装得下
            curv+=G[i].v;
            curm+=G[i].m;
        }else{//如果只装得下一部分
            curv+=(T-curm)*G[i].p;
            break;
        }
    }
    cout<<fixed<<setprecision(2)<<curv<<endl;
}

练习 排队打水 P1223 【第二关键词排序】

https://www.luogu.com.cn/problem/P1223

cpp 复制代码
using namespace std;
struct Node {
    int idx, t;
};
bool cmp(Node& a, Node& b) {
    return a.t < b.t;//输出时间小的优先
}
int n;
int main() {
    //SJF模型
    //
    cin >> n;
    vector<Node> P(n);
    for (int i = 0; i < n; i++) {
        cin >> P[i].t; P[i].idx = i;
    }
    sort(P.begin(), P.end(), cmp);
    double T = 0;
    double cur_t = 0;
    for (int i = 0; i < n; i++) {
        cout << P[i].idx+1 << " ";
        if (i >= 1) {
            cur_t += P[i - 1].t;
            T += cur_t;
            //cout << "T is:" << T << endl;
        }
    }
    cout << endl;
    cout << fixed << setprecision(2) << (double)T / n << endl;;
}