### 题目描述 ## Problem B: Jogging Trails

Gord is training for a marathon. Behind his house is a park with a large network of jogging trails connecting water stations. Gord wants to find the shortest jogging route that travels along every trail at least once.

Input consists of several test cases. The first line of input for each case contains two positive integers: n <= 15, the number of water stations, and m < 1000, the number of trails. For each trail, there is one subsequent line of input containing three positive integers: the first two, between 1 and n, indicating the water stations at the end points of the trail; the third indicates the length of the trail, in cubits. There may be more than one trail between any two stations; each different trail is given only once in the input; each trail can be travelled in either direction. It is possible to reach any trail from any other trail by visiting a sequence of water stations connected by trails. Gord’s route may start at any water station, and must end at the same station. A single line containing 0 follows the last test case.

For each case, there should be one line of output giving the length of Gord’s jogging route.

4 5
1 2 3
2 3 4
3 4 5
1 4 10
1 3 12
0

41

### 代码如下

``````#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int maxn = 15+1;
const int maxm = 1<<maxn;
struct Node
{
int pos, dist;
Node (int pos, int dist)
{
this->pos = pos;
this->dist = dist;
}
bool operator<(const struct Node &ans)const
{
return dist > ans.dist;
}
};
int degree[maxn], edge[maxn][maxn], dis[maxm];
bool vis[maxm];
int n, m, st, ed, sum;

void Init()
{
for(int i = 0; i < n; i++)
{
degree[i] = 0;
for(int j = 0; j < n; j++)
edge[i][j] = -1;
}

int a, b, c;
sum = 0;
for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &c);
a--, b--;
degree[a]++, degree[b]++;
sum += c;
if(edge[a][b] == -1 || edge[a][b] > c)
edge[a][b] = edge[b][a] = c;
}

st = ed = 0;
for(int i = 0; i < n; i++)
{
ed |= (1<<i);//终点为全1，即所有点的度都为偶数
if(degree[i] % 2 == 0)
st |= (1<<i);//起点为原图的点的奇偶性
}
}

void Dijkstra()
{
priority_queue<struct Node> myQue;
int up = 1 << n;
for(int i = 0; i < up; i++)
dis[i] = -1, vis[i] = false;

dis[st] = sum;
myQue.push(Node(st, dis[st]));
while(!myQue.empty())
{
Node ans = myQue.top();
myQue.pop();
int u = ans.pos;
if(vis[u])
continue;
vis[u] = true;
if(u == ed)
break;
for(int i = 0; i < n; i++)
for(int j = 0; j < i; j++)
{
if(edge[i][j] != -1)
{
int v = u ^ (1<<i);
v = v ^ (1<<j);//两个点取反达到下一个点
if(dis[v] == -1 || dis[u] + edge[i][j] < dis[v])
{
dis[v] = dis[u] + edge[i][j];
myQue.push(Node(v, dis[v]));
}
}
}
}
}

int main()
{
while(scanf("%d", &n) != EOF && n)
{
scanf("%d", &m);
Init();
Dijkstra();
printf("%d\n", dis[ed]);
}
return 0;
}  ``````