NYOJ 832 合并游戏(状态压缩)

来源:互联网 发布:2016淘宝小号直销商 编辑:程序博客网 时间:2024/05/21 07:05

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=832
状态压缩入门题;dp【st】 表示状态st时得到最大金币, st化成二进制, 0 表示把当前位和其他位合并,当前位石子消失;
举个例子: 当前状态【1 0 0】 就有状态【1 0 1】 + max(sa[j][i])和状态【1 1 0】 +max(sa[j][i]); j为当前状态所有为1的位。

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int maxn = 15;int dp[1<<maxn];int sa[maxn][maxn];int main(){    int n;    while(~scanf("%d", &n))    {        for(int i = 0; i < n; i++)            for(int j = 0; j < n; j++)                scanf("%d", &sa[i][j]);        memset(dp, 0, sizeof(dp));        int ans = 0;        for(int st =(1<<n)-1; st >= 1; st--)        {            for(int i = 0; i < n; i++)                if((st&(1<<i)) == 0)                {                    int temp = -1;                    for(int j = 0; j < n; j++)                    {                        if(st & (1<<j))                            temp = max(temp, sa[j][i]);                    }                    dp[st] = max(dp[st], dp[st|(1<<i)]+temp);                }            ans = max(ans, dp[st]);        }        printf("%d\n", ans);    }    return 0;}
0 0