BZOJ 3312 [Usaco2013 Nov]No Change

来源:互联网 发布:世界城市经纬度数据库 编辑:程序博客网 时间:2024/06/05 14:46

Description

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.

K个硬币,要买N个物品。

给定买的顺序,即按顺序必须是一路买过去,当选定买的东西物品序列后,付出钱后,货主是不会找零钱的。现希望买完所需要的东西后,留下的钱越多越好,如果不能完成购买任务,输出-1

Input

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. 

Output

* Line 1: The maximum amount of money FJ can end up with, or -1 if FJ cannot complete all of his purchases.

Sample Input

3 6
12
15
10
6
3
3
2
3
7

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.

Sample Output

12
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.

HINT

Source

窝想到了要状压硬币,再开一位表示剩下多少钱,但是mle。
苟且的看了题解,发现可以预处理第i个硬币从j开始拿最多可以拿多少个物品,记得要优化,时间复杂度可以从O(n^3)下降到O(n^2)。
#include<iostream>#include<cstdio>using namespace std;const int N=100005;int n,m,ans=-1,sum,v[17],s[N],c[N],g[17][N],f[1<<16];int main(){scanf("%d%d",&m,&n);for(int i=0;i<m;i++){scanf("%d",&v[i]);sum+=v[i];}for(int i=1;i<=n;i++){scanf("%d",&c[i]);s[i]=s[i-1]+c[i];}for(int i=0;i<m;i++)for(int j=1;j<=n;j++){int t=j+max(g[i][j-1]-2,0),lft=v[i]+s[j-1]-s[t-1];g[i][j]=max(0,g[i][j-1]-2);for(int k=t;k<=n;k++)if(lft>=c[k]){lft-=c[k];g[i][j]++;}elsebreak;}int end=(1<<m)-1;for(int i=0;i<=end;i++)for(int j=0;j<m;j++)if(!(i&(1<<j)))f[i|(1<<j)]=max(f[i|(1<<j)],f[i]+g[j][f[i]+1]);for(int i=0;i<=end;i++)if(f[i]==n){int t=0;for(int j=0;j<m;j++)if(i&(1<<j))t+=v[j];ans=max(ans,sum-t);}printf("%d\n",ans);return 0;}


0 0