洛谷P1208 混合牛奶(贪心)

地址:https://www.luogu.com.cn/problem/P1208

解析:

单价p,可完成数x

要想保证花费最少,有贪心思路:

1:单价从小到大排列。保证花费最小

2:单价相同,可完成数从大到小排列。保证能尽量多的用花费少的一方。

#include<cstdio>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;//优先为小的优先队列 
typedef long long ll;
const int maxn=5e3+20;
ll a[maxn];
struct node
{
    int p,x;
}st[maxn];
bool cmp(node a , node b)
{
    if(a.p==b.p)
        return a.x>b.x;
    return a.p<b.p;
}
int main()
{    // 4 0 20
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
        cin>>st[i].p>>st[i].x;
    sort(st+1,st+1+m,cmp);
    int sum=0;
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(ans==n)
            break;
        while(st[i].x)
        {
            if(ans==n)
                break;
            st[i].x--;
            ans++;
            sum+=st[i].p;
        }
    }
    cout<<sum<<endl;
}
原文地址:https://www.cnblogs.com/liyexin/p/13276731.html