这道题一看就是贪心题
先买便宜的牛奶,但如果牛奶的价钱一样,就先去买牛奶数量多的
这样写实在是太简洁了
尤其是这段代码
inline bool cmp(node x, node y){
if(x.p != y.p) return x.p < y.p;
return x.a > y.a;
}
#include<bits/stdc++.h>
#define ll long long
#define maxn 5005
using namespace std;
inline int read(){
int x = 0; bool f = false; char ch = getchar();
while(!isdigit(ch)){if(ch == '-') f = true; ch = getchar();}
while(isdigit(ch)){x = x * 10 + ch - '0'; ch = getchar();}
return f ? -x : x;
}
inline void write(ll x){
if (x < 0) x = ~x + 1, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, ans;
struct node{
int p, a;
}milk[maxn];
inline bool cmp(node x, node y){
if(x.p != y.p) return x.p < y.p;
return x.a > y.a;
}
int main(){
n = read(), m = read();
for(register int i = 1; i <= m; ++i) milk[i].p = read(), milk[i].a = read();
sort(milk + 1, milk + m + 1, cmp);
int i = 1;
while(n){
if(milk[i].a){
--milk[i].a;
ans += milk[i].p;
--n;
}
else ++i;
}
write(ans);
puts("");
return 0;
}
也可以用队列+ p a i r pair pair
#include<bits/stdc++.h>
#define ll long long
using namespace std;
inline int read(){
int x = 0; bool f = false; char ch = getchar();
while(!isdigit(ch)){if(ch == '-') f = true; ch = getchar();}
while(isdigit(ch)){x = x * 10 + ch - '0'; ch = getchar();}
return f ? -x : x;
}
inline void write(ll x){
if (x < 0) x = ~x + 1, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
priority_queue<pair<int, int> > q;
int n, m, ans, p, a, milk_quantity;
int main(){
n = read(), m = read();
if(!n){puts("0"); return 0;}
for(register int i = 1; i <= m; ++i){
p = read(); a = read();
q.push(make_pair(-p, a));//小技巧:存负边,保证取出的是最小值,你愿意也可以写个运算重载符
}
while(true){
if(milk_quantity + q.top().second >= n){
ans += (n - milk_quantity) * (-q.top().first);//注意存的是负边,取时要变正号,下同
write(ans);
puts("");
return 0;
}
milk_quantity += q.top().second;
ans += q.top().second * (-q.top().first);
q.pop();
}
}