HDU 3001 Travelling 状态压缩DP简单题

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int inf = 1000000009;
int map[13][13];
int cst[13];
int f[60004][13];
int dp[60004][13];
int n, m;
void init() {
	int i, j;
	cst[0] = 1;
	for(i = 1; i <= 10; i++) cst[i] = cst[i-1]*3;
	for(i = 0; i <= cst[10]; i++) {
		int t = i;
		for(j = 0; j < 10; j++) {
			f[i][j] = t % 3;
			t /= 3;
		}
	}
}
int main() {
	int i, j, k;
	init();
	while( ~scanf("%d%d", &n, &m)) {
		for(i = 0; i < n; i++)
			for(j = 0; j < n; j++)
				map[i][j] = inf;
		while(m--) {
			int x, y, z;
			scanf("%d%d%d", &x, &y, &z);
			 x--; y--;
			map[y][x] = map[x][y] = min(map[x][y], z);
		}
		for(i = 0; i < cst[n]; i++)
            for(j  = 0; j < n; j++)
                dp[i][j] = inf;

		for(i = 0; i < n; i++)
			dp[cst[i]][i] = 0;

        for(i = 0; i < cst[n]; i++)
            for(j = 0; j < n; j++) if(f[i][j] && dp[i][j] != inf)
                for(k = 0; k < n; k++) if(j != k && map[j][k] != inf && f[i][k] != 2) {
                    dp[i+cst[k]][k] = min(dp[i+cst[k]][k], dp[i][j] + map[j][k]);
                }
        int ans = inf;
        for(i = 0; i < cst[n]; i++)
            for(j = 0; j < n; j++) {
                for(k = 0; k < n; k++)
                    if(!f[i][k]) break;
                if(k == n) ans = min(ans, dp[i][j]);
            }
        if(ans == inf) ans = -1;
        printf("%d\n", ans);

	}
	return 0;
}

你可能感兴趣的:(HDU 3001 Travelling 状态压缩DP简单题)