洛谷 P2983 [USACO10FEB]购买巧克力Chocolate Buying
购买巧克力Chocolate Buying
乍一看以为是背包,然后交了一个感觉没错的背包上去。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//Mystery_Sky
//
#define M 10000000
#define ll long long
ll f[M];
ll p[M], num[M], sum;
ll n, v;
int main() {
scanf("%lld%lld", &n, &v);
for(int i = 1; i <= n; i++) scanf("%lld%lld", &p[i], &num[i]);
for(int i = 1; i <= n; i++) {
for(ll k = 1; k <= num[i]; k++) {
for(ll j = v; j >= p[i]; j--) {
f[j] = max(f[j], f[j-p[i]]+1);
}
}
}
printf("%lld\n", f[v]);
return 0;
}
结果无情30分。
看了一下数据范围,再仔细想了下,发现不是dp,贪心就可以了,从小到大排序费用,再从小到大买,到买不起为止即可。
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//Mystery_Sky
//
#define ll long long
#define M 1000000
struct node {https://i.cnblogs.com/EditCategories.aspx?catid=1
ll p, c;
}m[M];
ll ans, b;
int n;
inline bool cmp(node a, node b)
{
return a.p < b.p;
}
int main() {
scanf("%d %lld", &n, &b);
for(int i = 1; i <= n; i++) scanf("%lld%lld", &m[i].p, &m[i].c);
sort(m+1, m+1+n, cmp);
for(int i = 1; i <= n; i++) {
if(b / m[i].p >= m[i].c) {
ans += m[i].c;
b -= m[i].p * m[i].c;
}
else {
ans += b / m[i].p;
break;
}
}
printf("%lld\n", ans);
return 0;
}
唯愿,青春不辜负梦想,未来星辰闪耀