Posted on 2012-04-26 11:27
lenohoo 阅读(192)
评论(0) 编辑 收藏 引用
Jogging Trails
Time Limit: 1000MS |
| Memory Limit: 65536K |
Total Submissions: 1710 |
| Accepted: 672 |
Description
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
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.
Output
For each case, there should be one line of output giving the length of Gord's jogging route.
Sample Input
4 5 1 2 3 2 3 4 3 4 5 1 4 10 1 3 12 0
Sample Output
41
Source
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int MAXN = 30;
const int inf = 999999999;
int dp[1<<15];
int deg[MAXN],e[MAXN][MAXN];
void floyd(int n){
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
e[i][j]=min(e[i][j],e[i][k]+e[k][j]);
}
int dfs(int s,int n){
if(!s) return 0;
if(dp[s]>0) return dp[s];
dp[s]=inf;
for(int i=0;i<n;i++)
if(s|(1<<i))
for(int j=i+1;j<n;j++)
if(s|(1<<j)){
int tmp=dfs(s^(1<<i)^(1<<j),n)+e[i][j];
if(dp[s]>tmp) dp[s]=tmp;
}
return dp[s];
}
int main(){
int n,m,ans,s,u,v,w;
while(~scanf("%d%d",&n,&m) && n){
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
e[i][j]=inf;
for(int i=0;i<n;i++) deg[i]=0;
ans=0;
while(m--){
scanf("%d%d%d",&u,&v,&w);
u--;v--;
if(e[u][v]>w) e[u][v]=e[v][u]=w;
ans+=w;deg[u]++;deg[v]++;
}
s=0;
for(int i=0;i<n;i++) if(deg[i]%2) s|=(1<<i);
memset(dp,-1,sizeof(dp));
ans+=dfs(s,n);
printf("%d\n",ans);
}
return 0;
}