题目描述
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.
FJ正在市场上为他的农场采购日用品,他口袋里有K(1<=K<=16)个硬币,每一个硬币的面值均在1~1,00,000,000之间。FJ有一个包含N(1<=N<=100,000)种待购物品的序列清单,其中第i种物品需要的钱数为c(i),(1<= c(i) <=10,000),在购物的过程中,物品必须按照清单顺序购买,他随时可以停下来用一枚硬币付一次钱,每次付钱的对象为从上次付钱之后至当前所有物品价值和(当然,他所付的硬币面值也必须足够大),不巧的是,市场上的商户们都没有零钱了,因此如果FJ给的硬币面值大于所购物品价值,他也不会得到找零!
请计算FJ完成N件物品的购物后,所能剩下的最大钱数。如果他无法买到所有物品,输出-1。
输入
* 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.
第1行:两个整数K,N;
第2~K+1行:每行为一个硬币面值;
第K+2~N+K+1行:这N行为FJ所要购买的N件物品的价值。
输出
* Line 1: The maximum amount of money FJ can end up with, or -1 if FJ cannot complete all of his purchases.
一行,即结束购物后FJ所剩余的最大钱数,输出-1表示他无法完成购物。
样例输入
样例输出
提示
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.
FJ spends his 10-unit coin on the first two purchases, then the 15-unit
【思想】1、状压DP:k<=16,因此想到状压。a[ i ]为i状态下,最大能达到哪个价值,如果达到n,则比较该状态下的价值和ans取较大值;
2、二分:添加coin[ j ]硬币后,最大能到哪个价值,从a[ i ]到n二分,注意l和r的取值;
3、注意细节,比如输出-1和ans==0不是一回事。。。。
【代码】
<span style="font-size:18px;">#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=(1<<(17));
int k,n,coin[101],w[100005],mx,a[101],d[maxn],ans=-1;
inline int get(){
char c;while(!isdigit(c=getchar()));
int v=c-48;while(isdigit(c=getchar()))v=v*10+c-48;
return v;
}
inline int getans(int x){
int t=0;for(int i=1;i<=k;++i)if(!(a[i]&x))t+=coin[i];
return t;
}
int main(){
memset(d,0,sizeof(d));
k=get();n=get();mx=1<<k;w[0]=0;
for(int i=1;i<=k;++i)coin[i]=get(),a[i]=(1<<(i-1));
for(int i=1;i<=n;++i)w[i]=w[i-1]+get();
for(int t=0;t<mx;++t){
if(d[t]==n)ans=max(ans,getans(t));
for(int j=1;j<=k;++j)if(!(a[j]&t)){
int nxt=t^a[j];
int l=d[t],r=n,mid;
while(l<r){
mid=(l+r+1)>>1;
if((w[mid]-w[d[t]])<=coin[j])l=mid;else r=mid-1;
}
d[nxt]=max(d[nxt],l);
}
}
if (ans==-1) printf("-1\n");else printf("%d\n",ans);
return 0;
}</span>