-
Notifications
You must be signed in to change notification settings - Fork 34
/
1086-Jogging-Trails.cpp
176 lines (115 loc) · 2.35 KB
/
1086-Jogging-Trails.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//The great chinese postman problem
#include <queue>
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#define set(x, n) (x ^ (1 << n))
#define check(x, n) (x & (1 << n))
using namespace std;
int n;
int ind;
int edge_count[1028];
long long floyd[1028][1028];
int ans;
long long dp[ 1 << 17];
int floyd_warshal()
{
long long t;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if(floyd[i][j] == 0) {
floyd[i][j] = INT_MAX;
}
}
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if(floyd[i][k] != INT_MAX and floyd[k][j] != INT_MAX) {
t = floyd[i][k] + floyd[k][j];
if(t < floyd[i][j]) {
floyd[i][j] = t;
}
}
}
}
}
}
long long chinese(int bit)
{
int x;
long long mini;
int i;
mini = INT_MAX;
if(bit == 0) {
return 0;
}
if(dp[bit] != -1) {
return dp[bit];
}
for(i = 1; i <= n; i++) {
if(check(bit, i)) {
break;
}
}
for (int j = i + 1; j <= n; j++) {
int temp = bit;
if(check(bit, i) and check(bit, j )) {
temp = set(temp, i);
temp = set(temp, j);
mini = min(mini, floyd[i][j] + chinese(temp));
}
}
return dp[bit] = mini;
}
int travel(int cs)
{
int x;
int y;
int start;
long long mini;
long long w;
int m;
int bit;
memset(edge_count, 0, sizeof edge_count);
memset(dp, -1, sizeof dp);
ans = 0;
bit = 0;
cin >> n; //no of joints
cin >> m; // no of streets
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
floyd[i][j] = INT_MAX;
}
}
for (int i = 0; i < m; i++) {
cin >> x; // street starting point
cin >> y; // street ending point
cin >> w; // street length
ans += w;
floyd[x][y] = min(w, floyd[x][y]);
floyd[y][x] = min(w, floyd[y][x]);
edge_count[x]++;
edge_count[y]++;
}
floyd_warshal(); // calculate the shortest path between all the joints
for (int i = 1; i <= n; i++) {
if(edge_count[i] % 2 == 1) {
bit = set(bit, i); // mark joints with odd degree
}
}
ans += chinese(bit); // try all combination of odd vertices and choose the combination with minimum distance
printf("Case %d: %d\n", cs, ans);
}
int main()
{
int t;
cin >> t; // no of test cases
for (int cs = 1; cs <= t; cs++) {
travel(cs);
}
}