题意:给定一个无相图,求从任意点为起点遍历所有边最后回到起点的最短距离
思路:
这题首先要知道,是要构造欧拉回路,然后我们找出所有奇度数的点,添加边使之变为偶度数
然后添加边就用状态压缩DP来做
AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 0x3f3f3f3f
vector<int> maps[17][17];
int dis[17][17];
int N, M;
int cnt[16];
int dp[17][1<<17];
vector<int> vis;
int K;
int solve( int pos, int statu ){
if( pos >= K ){
return 0;
}
if( statu & ( 1 << pos ) ){
return solve( pos + 1, statu );
}
if( dp[pos][statu] != -1 ){
return dp[pos][statu];
}
int ans = MAX;
for( int i = pos + 1; i < K; i++ ){
if( statu & ( 1 << i ) ) continue;
ans = min( ans, solve( pos + 1, statu | ( 1 << pos ) | ( 1 << i ) ) + dis[vis[i]][vis[pos]] );
}
return dp[pos][statu] = ans;
}
int main(){
int T, Case = 1, sum;
scanf( "%d", &T );
while( T-- ){
scanf( "%d%d", &N, &M );
for( int i = 1; i <= N; i++ ){
for( int j = 1; j <= N; j++ ){
maps[i][j].clear();
maps[i][j].push_back( MAX );
}
}
sum = 0;
memset( cnt, 0, sizeof( cnt ) );
for( int i = 0; i < M; i++ ){
int temp1, temp2, temp3;
scanf( "%d%d%d", &temp1, &temp2, &temp3 );
maps[temp1][temp2].push_back( temp3 );
maps[temp1][temp2][0] = min( maps[temp1][temp2][0], temp3 );
maps[temp2][temp1].push_back( temp3 );
maps[temp2][temp1][0] = min( maps[temp2][temp1][0], temp3 );
cnt[temp1]++;
cnt[temp2]++;
sum += temp3;
}
for( int i = 1; i <= N; i++ ){
for( int j = 1; j <= N; j++ ){
if( i == j ){
dis[i][j] = 0;
}else{
dis[i][j] = maps[i][j][0];
}
}
}
// cout << dis[1][2] << " " << dis[1][3] << " " << dis[2][3] << endl;
for( int k = 1; k <= N; k++ ){
for( int i = 1; i <= N; i++ ){
for( int j = 1; j <= N; j++ ){
dis[i][j] = min( dis[i][j], dis[i][k] + dis[k][j] );
}
}
}
// cout << dis[1][2] << " " << dis[1][3] << " " << dis[2][3] << endl;
K = 0;
vis.clear();
for( int i = 1; i <= N; i++ ){
if( cnt[i] % 2 == 1 ){
vis.push_back( i );
// cout << i << endl;
K++;
}
}
int ans = 0;
memset( dp, -1, sizeof( dp ) );
ans = sum + solve( 0, 0 );
printf( "Case %d: %d\n", Case++, ans );
}
return 0;
}
/*
1
3 4
1 3 3
1 3 12
1 2 10
2 3 13
*/