其他分享
首页 > 其他分享> > NC24416 [USACO 2013 Nov G]No Change

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.

输入描述

输出描述

示例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解法。

时间复杂度 \(O(m2^m\log n)\)

空间复杂度 \(O(n+2^m)\)

代码

#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;
}

标签:purchases,his,No,int,money,USACO,12,FJ,2013
来源: https://www.cnblogs.com/BlankYang/p/16654154.html