HDU 3001 状压(三进制)

/*
状压DP。
三进制表示访问几次
*/

#include <bits/stdc++.h>
using namespace std;
#define inf ((long long)1000000007 * 1000000007)
#define LL long long
const int MAXN = 10 + 2;
const int MAXM = 120000;
LL dp[MAXM][MAXN];
LL g[MAXN][MAXN];
int thr[MAXN];
int n, m;
void init()
{
    thr[0] = 1;
    for(int i = 1 ; i < MAXN ; i++) thr[i] = thr[i - 1] * 3;
}
int main()
{
    init();
    while(scanf("%d%d", &n, &m) != EOF) {
        memset(g, -1, sizeof g);
        for(int i = 0 ; i < n ; i++) g[i][i] = 0;
        for(int i = 0 ; i < m ; i++) {
            int u, v;
            LL w;
            scanf("%d%d%I64d", &u, &v, &w); u--, v--;
            if(g[u][v] == -1 || g[u][v] > w) {
                g[u][v] = g[v][u] = w;
            }
        }

        memset(dp, -1, sizeof dp);
        for(int i = 0 ; i < n ; i++) dp[thr[i]][i] = 0;
        for(int i = 0 ; i < thr[n] ; i++) {
            for(int j = 0 ; j < n ; j++) {
                if((i / thr[j]) % 3 == 0 || dp[i][j] == -1) continue;
                for(int k = 0 ; k < n ; k++) {
//                    if(i == 1) {
//                        printf("ts = %d, i / thr[k] % 3 = %d, j = %d\n", i + thr[k], (i / thr[k]) % 3, j);
//                        printf("thr[k] = %d, k = %d, g[j][k] = %I64d\n", thr[k], k, g[j][k]);
//                    }
                    if((i / thr[k]) % 3 == 2 || g[j][k] == -1) continue;
                    int ts = i + thr[k];
//                    if(i == 1)
//                    printf("ts = %d\n", ts);
                    if(dp[ts][k] == -1 || dp[ts][k] > dp[i][j] + g[j][k]) {
//                        printf("i = %d, j = %d, ts = %d, k = %d\n", i, j, ts, k);
                        dp[ts][k] = dp[i][j] + g[j][k];
                    }
//                    system("pause");
                }
            }
        }
        LL ans = -1;
        for(int i = 0 ; i < n ; i++) {
            LL temp = dp[thr[n] - 1][i];
            if(temp != -1)
                if(temp < ans || ans == -1) ans = temp;
        }
        printf("%I64d\n", ans);
    }
    return 0;
}

你可能感兴趣的:(HDU 3001 状压(三进制))