1. 程式人生 > 實用技巧 >洛谷P1208 混合牛奶(貪心)

洛谷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; }