BZOJ 4145 [AMPPZ2014]The Prices (状压DP)

一般的思路是\(dp[i][j]\)代表前i个商店购买集合为j的最小费用,枚举每一个商店然后枚举子集。复杂度\(O(nm^3)\)过不了。
先把\(dp[i][j]\)设为\(dp[i-1][j]\)表示钦定在这个商店购物,然后在\(dp[i]\)中做背包。
具体就是枚举每一个商品买不买。
然后惊奇的发现这样复杂度为\(O(nmm^2)\)可以通过本题。

#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
const int N=70000;
int n,m,d[110],c[110][20],dp[2][N];
int read(){
    int sum=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
    return sum*f;
}
int main(){
    n=read();m=read();
    for(int i=1;i<=n;i++){
        d[i]=read();
        for(int j=1;j<=m;j++)
            c[i][j]=read();
    }
    memset(dp,0x3f,sizeof(dp));
    dp[0][0]=0;
    for(int i=1;i<=n;i++){
        for(int j=0;j<(1<<m);j++)
            dp[i&1][j]=dp[(i&1)^1][j]+d[i];
        for(int j=1;j<=m;j++)
            for(int k=1;k<(1<<m);++k)
                if(k&(1<<j-1))
                    dp[i&1][k]=min(dp[i&1][k],dp[i&1][k^(1<<j-1)]+c[i][j]);
        for(int j=0;j<(1<<m);j++)
            dp[i&1][j]=min(dp[i&1][j],dp[(i&1)^1][j]);
    }
    printf("%d\n",dp[n&1][(1<<m)-1]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Xu-daxia/p/10468802.html