24h購物| | PChome| 登入
2012-04-28 17:34:50| 人氣1,955| 回應0 | 上一篇 | 下一篇

[UVA][中國郵路問題] 10296 - Jogging Trails

推薦 0 收藏 0 轉貼0 訂閱站台

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.

Sample Input

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

Output for Sample Input

41


利用尤拉環道的概念, 每個節點都必須有偶數個 deg,
在此題中, 如果產生奇數 deg 的點, 則將其兩兩匹配, 使其圖變成尤拉環道,
其匹配的成本越小越好
#include <stdio.h>
#include <string.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
int map[16][16], odd[16];
void floyd(int n) {
int i, j, k;
for(k = 1; k <= n; k++)
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
map[i][j] = min(map[i][j], map[i][k]+map[k][j]);
}
int dp[1<<16];
int build(int pN, int ot) {
if(pN == 0)
return 0;
if(dp[pN] != -1)
return dp[pN];
int i, j, tmp;
dp[pN] = 0xfffffff;
for(i = 0; i < ot; i++) {
if(pN&(1<<i)) {
for(j = i+1; j < ot; j++) {
if(pN&(1<<j)) {
tmp = build(pN-(1<<i)-(1<<j), ot);
dp[pN] = min(dp[pN], tmp+map[odd[i]][odd[j]]);
}
}
break;
}
}
return dp[pN];
}
int main() {
int n, m, x, y, w;
while(scanf("%d", &n) == 1 && n) {
scanf("%d", &m);
memset(map, 63, sizeof(map));
memset(dp, -1, sizeof(dp));
int sum = 0, deg[16] = {};
while(m--) {
scanf("%d %d %d", &x, &y, &w);
map[x][y] = min(map[x][y], w);
map[y][x] = min(map[y][x], w);
deg[x]++, deg[y]++;
sum += w;
}
floyd(n);
int ot = 0;
for(int i = 1; i <= n; i++)
if(deg[i]&1)
odd[ot++] = i;
printf("%d\n", sum+build((1<<ot)-1, ot));
}
return 0;
}
 

台長: Morris
人氣(1,955) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][迴文] 11309 - Counting Chaos
此分類上一篇:[UVA][Math] 11152 - Colourful Flowers

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文