zoj 2109 FatMouse' Trade 部分背包
部分背包问题,贪心
先按J[i] / F[i] 升序排序,每次选取J[i] / F[i]的最大值,如果不能取满J[i],则取把背包填满的容量即可。原因很简单,每次取J[i] / F[i]的最大值就使得背包单位体积价值最多。从大到小选择,自然会得到最优解。
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; const int N = 1005; struct info { int j, f; double divid; }; info a[N]; bool cmp(const info& a, const info& b) { return a.divid > b.divid; } int main() { int m, n; while (scanf("%d%d", &m, &n)) { if (m == -1 && n == -1) break; for (int i = 1; i <= n; i++) { scanf("%d%d", &a[i].j, &a[i].f); a[i].divid = (double)a[i].j / a[i].f; } int beans = 0, catfood = 0; int i; sort(a+1, a+n+1, cmp); for (i = 1; i <= n; i++) { beans += a[i].j; catfood += a[i].f; if (catfood > m) { catfood -= a[i].f; beans -= a[i].j; break; } } if (i <= n) beans += (double)(m - catfood)/a[i].f * a[i].j; printf("%.3lf\n", beans); } return 0; }