hdu 3001 Travelling//状态压缩DP




#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int inf = 100000000;
int tri[12] = {0,1,3,9,27,81,243,729,2187,6561,19683,59049};
int map[12][12];
int dig[59049][11];
int dp[59049][11];
int main()
{
    for(int i = 0; i < 59049; i++)
    {
        int temp = i;
        for(int j = 1; j <= 10; j++)
        {
            dig[i][j] = temp % 3;
            temp = temp / 3;
            if(temp == 0)  break;
        }
    }

    int n, m;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                map[i][j] = inf;

        int a, b, c;
        while(m--)
        {
            scanf("%d%d%d", &a, &b, &c);
            map[a][b] = map[b][a] = min(map[a][b], c);//重边
        }

        memset(dp, -1, sizeof(dp));
        for(int i = 1; i <= n; i++)  dp[tri[i]][i] = 0;

        int ans = inf;

        for(int i = 0; i < tri[n+1]; i++)
        {
            bool flag = true;
            for(int j = 1; j <= n; j++)
            {
                if(dig[i][j] == 0)  flag = false;//判断是不是全都搞定了
                if(dp[i][j] == -1)  continue;

                for(int k = 1; k <= n; k++)
                {
                    if(k == j)  continue;
                    if(map[j][k] == inf || dig[i][k] >= 2)  continue;
                    int temp = i + tri[k];
                    if(dp[temp][k] == -1)  dp[temp][k] = dp[i][j] + map[j][k];
                    else dp[temp][k] = min(dp[temp][k], dp[i][j] + map[j][k]);
                }
            }

            if(flag)
            {
                for(int j = 1; j <= n; j++)
                if(dp[i][j] != -1)
                    ans = min(ans, dp[i][j]);
            }
        }

        if(ans == inf)  puts("-1");
        else printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(hdu 3001 Travelling//状态压缩DP)