codeforce 580D Kefa and Dishes (状压DP)

原题地址:http://codeforces.com/contest/580/problem/D

 

题意:

 

题解

状压DP

 

/* http://codeforces.com/contest/580/problem/D */

#include<bits/stdc++.h>

#define clr(x,y) memset((x),(y),sizeof(x))

using namespace std;
typedef long long LL;

const int maxn=1<<18;

LL dp[maxn+5][20];
LL A[20];
LL B[20][20];

int Count(int x)
{
    int res=0;
    while (x>0)
    {
        x-=x&(-x);
        ++res;
    }
    return res;
}

int n,m,k;

int main(void)
{
    #ifdef ex
    freopen ("../in.txt","r",stdin);
    //freopen ("../out.txt","w",stdout);
    #endif

    int p,q;
    LL t;

    scanf("%d%d%d",&n,&m,&k);
    for (int i=0;i<=n-1;++i)
    {
        scanf("%I64d",&A[i]);
    }
    for (int i=1;i<=k;++i)
    {
        scanf("%d%d%I64d",&p,&q,&t);
        B[p-1][q-1]=t;
    }

    LL ans=0;
    clr(dp,0);
    for (int i=0;i<=n-1;++i)
    {
        dp[1<<i][i]=A[i];
    }
    int s=(1<<n)-1;
    for (int mask=0;mask<=s;++mask)
    {
        for (int i=0;i<=n-1;++i)
        {
            if (mask>>i & 1)
            {
                for (int j=0;j<=n-1;++j)
                {
                    if (!(mask>>j & 1))
                    {
                        dp[mask|1<<j][j]=max(dp[mask|1<<j][j],dp[mask][i]+B[j][i]+A[j]);
                    }
                }
            }
        }
    }

    for (int mask=0;mask<=s;++mask) /*处理完了之后再更新答案,可以避免遗漏*/
    {
        if (Count(mask)==m)
        for (int i=0;i<=n-1;++i)
        {
            ans=max(ans,dp[mask][i]);
        }
    }
    printf("%I64d\n",ans);
}

 

posted on 2016-06-09 21:52  zhong_wang  阅读(146)  评论(0编辑  收藏  举报

导航