Luogu3092 [USACO13NOV]没有找零No Change (状压DP)

将金币状压,然后就没多说的了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

//#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

int a[100007], sum[100007], coin[17];
int bin[17];
int f[(1 << 16)+7];
int main(){
	FileOpen();
	int m, n;
    io >> m >> n;
    int totalMoney = 0;
    R(i,1,m){
        io >> coin[i];
        totalMoney += coin[i];
    }
    R(i,1,n){
    	io >> a[i];
    	sum[i] += sum[i - 1] + a[i];
    }
    
    bin[1] = 1;
    R(i,2,m) bin[i] = bin[i - 1] << 1;
    
    int maxx = (1 << m) - 1;
    R(i,0,maxx){
    	R(j,1,m){
    		if(i & bin[j]){
    			int tmp = upper_bound(sum + 1, sum + n + 1, sum[f[i ^ bin[j]]] + coin[j]) - sum;
    			f[i] = Max(f[i], tmp - 1);
    		}
    	}
    }
    
    int ans = -1;
    R(i,0,maxx){
    	if(f[i] == n){
    		int totalCost = 0;
    		R(j,1,m){
    			if(i & bin[j]){
    				totalCost += coin[j];
    			}
    		}
    		ans = Max(ans, totalMoney - totalCost);
    	}
    }
    
    if(ans < 0)
    	printf("-1");
    else
    	printf("%d", ans);
    
    return 0;
}

posted @ 2019-07-21 16:32  邱涵的秘密基地  阅读(127)  评论(0编辑  收藏  举报