NC24416 [USACO 2013 Nov G]No Change
题目
题目描述
Farmer John is at the market to purchase supplies for his farm. He has in his pocket K coins (1 <= K <= 16), each with value in the range 1..100,000,000. FJ would like to make a sequence of N purchases (1 <= N <= 100,000), where the ith purchase costs c(i) units of money (1 <= c(i) <= 10,000). As he makes this sequence of purchases, he can periodically stop and pay, with a single coin, for all the purchases made since his last payment (of course, the single coin he uses must be large enough to pay for all of these). Unfortunately, the vendors at the market are completely out of change, so whenever FJ uses a coin that is larger than the amount of money he owes, he sadly receives no changes in return!
Please compute the maximum amount of money FJ can end up with after making his N purchases in sequence. Output -1 if it is impossible for FJ to make all of his purchases.
输入描述
-
Line 1: Two integers, K and N.
-
Lines 2..1+K: Each line contains the amount of money of one of FJ's
coins. -
Lines 2+K..1+N+K: These N lines contain the costs of FJ's intended
purchases.
输出描述
- Line 1: The maximum amount of money FJ can end up with, or -1 if FJ
cannot complete all of his purchases.
示例1
输入
3 6 12 15 10 6 3 3 2 3 7
输出
12
说明
INPUT DETAILS:
FJ has 3 coins of values 12, 15, and 10. He must make purchases in
sequence of value 6, 3, 3, 2, 3, and 7.
OUTPUT DETAILS:
FJ spends his 10-unit coin on the first two purchases, then the 15-unit
coin on the remaining purchases. This leaves him with the 12-unit coin.
题解
知识点:状压dp,二分。
先前缀和货物价值,方便查找加能到达的不大于上一次价值加上硬币价值的最大货物价值,之后就是个TSP解法。
时间复杂度
空间复杂度
代码
#include <bits/stdc++.h> #define ll long long using namespace std; int c[20], a[100007], dp[(1 << 16) + 7]; int main() { std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int m, n; cin >> m >> n; for (int i = 1;i <= m;i++) cin >> c[i]; for (int i = 1;i <= n;i++) cin >> a[i], a[i] += a[i - 1]; ll ans = -1; for (int i = 0;i < (1 << m);i++) { ll sum = 0; for (int j = 1;j <= m;j++) { if (!(i & (1 << (j - 1)))) { sum += c[j]; continue; } int k = upper_bound(a + 1, a + n + 1, a[dp[i ^ (1 << (j - 1))]] + c[j]) - a - 1; dp[i] = max(dp[i], k); } if (dp[i] == n) ans = max(ans, sum); } cout << ans << '\n'; return 0; }
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16654154.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧