-
Notifications
You must be signed in to change notification settings - Fork 34
/
1057-Collecting-Gold.cpp
117 lines (82 loc) · 1.41 KB
/
1057-Collecting-Gold.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
#include <iostream>
#include <vector>
#include <utility>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int n;
int k;
int vis[20];
int a[20][20];
int ans[20][(1 << 16) + 1];
int check(int x, int i)
{
return (x & (1 << i));
}
int set(int x, int i)
{
x = x ^ (1 << i);
return x;
}
int explore(int i, int x)
{
int k;
int temp;
k = 1 << (n + 1);
k--;
if(x == k) {
return a[i][0];
}
if(ans[i][x] != -1) {
return ans[i][x];
}
int mini = INT_MAX;
for (int j = 1; j <= n; j++) {
if(vis[j] == 0) {
x = set(x, j);
vis[j] = 1;
temp = a[i][j] + explore(j, x);
mini = min(mini, temp);
x = set(x, j);
vis[j] = 0;
}
}
ans[i][x] = mini;
return mini;
}
int main()
{
int r;
int c;
int t;
char cc;
scanf("%d", &t);
for (int cs = 1; cs <= t; cs++) {
scanf("%d", &r);
scanf("%d", &c);
vector <pair <int, int> > gr(20);
n = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> cc;
if(cc == 'x') {
gr[0] = make_pair(i, j);
continue;
}
if(cc == 'g') {
n++;
gr[n] = make_pair(i, j);
}
}
}
for (int i = 0; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
a[i][j] = a[j][i] = max(abs(gr[i].first - gr[j].first) , abs(gr[i].second - gr[j].second));
}
}
memset(ans, -1, sizeof(ans));
printf("Case %d: %d\n",cs, explore(0, 1));
}
}