洛谷1417(排序后背包)
一看很像背包,然而值却是会随时间递减的(a - t*b),不能满足无后效性,于是考虑常用手段,先按照优先级排序。
这个优先级怎么定呢?列式子模拟一下。
洛谷题解说得很好了:
说来惭愧,其实这种“组合式”排序我也是第一次见,虽然很好理解:
1 bool operator < (const food& rhs) const { 2 return (long long)b * rhs.c > (long long)rhs.b * c; 3 }
最后记得各种longlong。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 const int maxn = 55; 6 int T, n; 7 long long dp[100005], ans; 8 struct food { 9 int a, b, c; 10 11 bool operator < (const food& rhs) const { 12 return (long long)b * rhs.c > (long long)rhs.b * c; 13 } 14 }f[maxn]; 15 16 int main() { 17 ios_base::sync_with_stdio(0); 18 cin.tie(0); 19 cout.tie(0); 20 21 cin >> T >> n; 22 for (int i = 1; i <= n; i++) cin >> f[i].a; 23 for (int i = 1; i <= n; i++) cin >> f[i].b; 24 for (int i = 1; i <= n; i++) cin >> f[i].c; 25 sort(f + 1, f + 1 + n); 26 27 for (int i = 1; i <= n; i++) { 28 for (int j = T; j >= f[i].c; j--) { 29 dp[j] = max(dp[j], dp[j - f[i].c] + f[i].a - (long long)j * f[i].b); 30 ans = max(ans, dp[j]); 31 } 32 } 33 cout << ans << endl; 34 return 0; 35 }