UVALive 6255 Kingdoms

来源:互联网 发布:联通语音网络类型 编辑:程序博客网 时间:2024/06/06 00:48

Problem

icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4266
vjudge.net/contest/191053#problem

Meaning

有 n 个国家,它们相互之间有债务关系(有正有负),如果一个国家付完所有债之后剩余负数的钱,那么它就会破产,破产的国家会消失,同时与它相关的债务关系全部消失(这样可能会使得另一个原本会破产的国家不破产,或原来不破产而变成破产)。国家消失的顺序不同,最后剩下的国家也会不同。
问有哪些国家可能成为唯一剩下的那个国家。

Analysis

考虑状压DP。
dp[s]:当前剩下的国家的集合是 s 时,可能成为唯一剩下的国家的集合
转移的时候,枚举当前存在且破产的国家,让它破产并深搜下去,把搜到的结果合并到当前的 dp[s] 中。

Code

#include <cstdio>#include <cstring>using namespace std;const int N = 20;int d[N][N], dp[1<<N], n;int dfs(int s, int r){    if(~dp[s])        return dp[s];    if(r == 1)        return dp[s] = s;    dp[s] = 0;    for(int i = 0; i < n; ++i)        if(s >> i & 1)        {            // 判断是否会破产            int sum = 0;            for(int j = 0; j < n; ++j)                if(s >> j & 1) // 存在的国家才有债务关系                    sum -= d[i][j];            if(sum < 0) // 会破产                dp[s] |= dfs(s ^ (1 << i), r - 1);        }    return dp[s];}int main(){    int T;    scanf("%d", &T);    while(T--)    {        scanf("%d", &n);        for(int i = 0; i < n; ++i)            for(int j = 0; j < n; ++j)                scanf("%d", d[i]+j);        memset(dp, -1, sizeof dp);        int ans = dfs((1 << n) - 1, n), cnt = 0;        for(int i = 0; i < n; ++i)            cnt += ans >> i & 1;        if(!cnt)            puts("0");        else            for(int i = 0; cnt; ++i)                if(ans >> i & 1)                    printf("%d%c", i + 1, --cnt ? ' ' : '\n');    }    return 0;}
原创粉丝点击