-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathf80789_9b.cpp
More file actions
121 lines (106 loc) · 1.65 KB
/
f80789_9b.cpp
File metadata and controls
121 lines (106 loc) · 1.65 KB
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
#include <cstdio>
#include <vector>
using namespace std;
struct Edge
{
int v, d;
Edge() {}
Edge(int v, int d)
{
this -> v = v;
this -> d = d;
}
};
const int N = 1 << 10;
const int INF = 1 << 30;
int m;
int n = 0;
vector <Edge> g[N];
vector <int> cycle;
vector <int> min_cycle;
bool used[N];
int current_sum;
int min_sum;
void input()
{
for (int i = 0; i < m; i++)
{
int u, v, d;
scanf("%d%d%d", &u, &v, &d);
g[u].push_back(Edge(v, d));
g[v].push_back(Edge(u, d));
if (u > n) n = u;
if (v > n) n = v;
}
}
void clean_graph()
{
for (int i = 1; i <= n; i++)
{
g[i].clear();
used[i] = 0;
}
n = 0;
}
void hamilton(int u, int level)
{
if (u == 1 && level > 0)
{
if (level == n)
{
min_sum = current_sum;
min_cycle.clear();
for (int i = 0; i < cycle.size(); i++)
{
min_cycle.push_back(cycle[i]);
}
}
return;
}
if (used[u]) return;
used[u] = 1;
for (int i = 0; i < g[u].size(); i++)
{
Edge e = g[u][i];
cycle.push_back(e.v);
current_sum += e.d;
if (current_sum < min_sum)
{
hamilton(e.v, level + 1);
}
cycle.pop_back();
current_sum -= e.d;
}
used[u] = 0;
}
void print_cycle()
{
if (min_cycle.size() > 2)
{
for (int i = 0; i < min_cycle.size() - 1; i++)
{
printf("%d ", min_cycle[i]);
}
printf("\n");
}
else
{
printf("-1\n");
}
}
int main()
{
while (scanf("%d", &m) != EOF)
{
input();
current_sum = 0;
min_sum = INF;
cycle.clear();
min_cycle.clear();
cycle.push_back(1);
hamilton(1, 0);
print_cycle();
clean_graph();
}
return 0;
}