-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsp.cpp
More file actions
67 lines (56 loc) · 1.26 KB
/
tsp.cpp
File metadata and controls
67 lines (56 loc) · 1.26 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
#include <bits/stdc++.h>
using namespace std;
int weight[1000][1000];
int added[1010];
void add(int index) {
added[index] = 1;
return ;
}
void rem(int index) {
added[index] = 0;
return;
}
int tsp(int index, int n) {
bool flag = false;
int min = INT_MAX;
int temp_index;
for (int i = 2; i <= n; i++) {
if (added[i] == 0) {
flag = true;
add(i);
int temp = weight[index][i] + tsp(i, n);
if(min >temp) {
//cout << index << " " << i << " " << added[3] << endl;
min = temp;
}
rem(i);
}
}
if (flag == false){
//cout << index << "end" << 1 << endl;
return weight[1][index];
}
return min;
}
int main()
{
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
int wight[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ( j!= i) {
printf("%d %d ", i, j);
scanf("%d",&wight[i][j] );
weight[i + 1][j + 1] = wight[i][j];
}
}
}
cout << endl;
add(1);
printf("%d\n", tsp(1, n));
}
}