HDU - 5418 Victor and World (TSP问题求最小哈密顿回路 floyd + 状压dp)
After trying hard for many years, Victor has finally received a pilot license. To have a celebration, he intends to buy himself an airplane and fly around the world. There are nn countries on the earth, which are numbered from 11 to nn . They are connected by mm undirected flights, detailedly the ii -th flight connects the uiui -th and the vivi -th country, and it will cost Victor's airplane wiwi L fuel if Victor flies through it. And it is possible for him to fly to every country from the first country.
Victor now is at the country whose number is 11 , he wants to know the minimal amount of fuel for him to visit every country at least once and finally return to the first country.
Input
The first line of the input contains an integer TT , denoting the number of test cases.
In every test case, there are two integers nn and mm in the first line, denoting the number of the countries and the number of the flights.
Then there are mm lines, each line contains three integers uiui , vivi and wiwi , describing a flight.
1≤T≤201≤T≤20 .
1≤n≤161≤n≤16 .
1≤m≤1000001≤m≤100000 .
1≤wi≤1001≤wi≤100 .
1≤ui,vi≤n1≤ui,vi≤n .
Output
Your program should print TT lines : the ii -th of these should contain a single integer, denoting the minimal amount of fuel for Victor to finish the travel.
Sample Input
1 3 2 1 2 2 1 3 3
Sample Output
10
题意:
无向图中有 n 个点 m 条边,求最小哈密顿回路的长度。
思路:
先用floyd求一遍最短路。
数据最大是16,用1 << n以内的数代表一个状态(图),dp[i][S]表示当前位于 i 点且走过的图为 S 的最小花费,然后再添加一条边,遍历起点 i 和终点 j ,更新 dp[j][S | (1 << j)](走过g[i][j]这条边后位于 j 点,走过的图是之前的S再加上 j 点)
然后 for 循环一遍每个点再回到起点的最小值
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = (1 << 16) + 10;
int t, n, m;
int dp[20][N], g[20][20];
void init()
{
memset(dp, inf, sizeof(dp));
memset(g, inf, sizeof(g));
}
void floyd()
{
for(int k = 0; k < n; ++k)
{
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
}
}
}
}
int main()
{
int u, v, w;
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; ++i)
{
scanf("%d%d%d", &u, &v, &w);
u--;
v--;
if(g[u][v] > w)
g[u][v] = g[v][u] = w;
}
floyd();
int bit = (1 << n);
dp[0][1] = 0;
for(int S = 1; S < bit; ++S)
{
for(int i = 0; i < n; ++i) ///起点
{
if(S & (1 << i)) ///S中包含第 i 个状态,即走过第 i 点
{
for(int j = 0; j < n; ++j) ///终点
{
if(!(S & (1 << j)) && g[i][j] != inf) ///之前没有走过 j 点且i到j之间有边
{
dp[j][S | (1 << j)] = min(dp[j][S | (1 << j)], dp[i][S] + g[i][j]); ///更新
}
}
}
}
}
int minn = inf;
g[0][0] = 0;
for(int i = 0; i < n; ++i)
{
minn = min(minn, dp[i][bit - 1] + g[0][i]); ///回到起点
}
cout<<minn<<'\n';
}
return 0;
}