50060. Traveling Salesman

難度:4/5

Second Try: 3/5 Used Tiem 12:48

Notice doing a pruning like

1
if(now_cost + g[0][arr[now_idx - 1]] > min_cost) return;
is wrong, because g[0][arr[now_idx - 1] would not be in the route, so adding this cost may let you find the right path but prune it thus it didn't count.

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
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <stdint.h>

int n;
int cost[16][16] = {0};
int min_cost = INT_MAX;

static inline int min(int a, int b){
if(a < b) return a;
return b;
}

void dfs(int now_pos, int visited_num, int visited[16], int now_cost){
if(now_cost >= min_cost) return;
if(visited_num == n){
now_cost += cost[now_pos][0];
min_cost = min(min_cost, now_cost);
return;
}

for(int i = 0; i < n; i++){
if(visited[i] == 1) continue;

visited[i] = 1;
dfs(i, visited_num + 1, visited, now_cost + cost[now_pos][i]);
visited[i] = 0;
}
}

int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%d", &cost[i][j]);
}
}
int visited[16] = {0};
visited[0] = 1;
dfs(0, 1, visited, 0);
printf("%d\n", min_cost);
}


50060. Traveling Salesman
https://aaronlin1229.github.io/judgegirl_50060/
Author
Akizumi
Posted on
July 17, 2023
Licensed under