题解|贪心
2026-06-22 22:09:39
发布于:上海
0阅读
0回复
0点赞
注意到单价的范围较小仅仅为[0,1000],可以考虑使用桶计数,表示单价为i的农户总共能提供多少粮草,以减少时间复杂度。该算法时间复杂度仅为O(m),属于最优级别,而常规的标准做法时间复杂度为O(mlogm)。
代码如下:
#include <bits/stdc++.h>
using namespace std;
int to[1005];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n,m;
cin >> n >> m;
for (int i = 0; i < m; i++){
int x,y;
cin >> x >> y;
to[x] += y;
}
int sum = 0,money = 0;
for(int i = 0; i <= 1000; i++){
if(to[i] >= n){
money += n*i;
break;
}
else{
money += to[i]*i;
n -= to[i];
}
}
cout << money;
return 0;
}
这里空空如也

有帮助,赞一个