Skip to content

Commit 4e94397

Browse files
authored
[20251128] BOJ / P4 / Island Travels / 권혁준
1 parent eb7fb26 commit 4e94397

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
```cpp
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
const int dx[4] = {1,0,-1,0};
6+
const int dy[4] = {0,1,0,-1};
7+
const int INF = 1e9 + 7;
8+
9+
int N, W, H;
10+
char arr[50][50]{};
11+
int num[50][50]{};
12+
bool vis[50][50]{};
13+
int cost[15][15]{};
14+
int dp[15][1<<15]{};
15+
vector<vector<pair<int, int>>> islands;
16+
17+
int get(int n, int k) {
18+
if(dp[n][k] != INF) return dp[n][k];
19+
int &ret = dp[n][k];
20+
int p = k ^ (1<<n);
21+
for(int i=0;i<N;i++) if((1<<i) & p) ret = min(ret, get(i,p) + cost[i][n]);
22+
return ret;
23+
}
24+
25+
int main(){
26+
cin.tie(0)->sync_with_stdio(0);
27+
28+
cin>>W>>H;
29+
for(int i=0;i<W;i++) for(int j=0;j<H;j++) cin>>arr[i][j], num[i][j] = -1;
30+
31+
for(int i=0;i<W;i++) for(int j=0;j<H;j++) if(arr[i][j] == 'X' && !vis[i][j]) {
32+
queue<pair<int, int>> q;
33+
q.emplace(i,j);
34+
vis[i][j] = 1;
35+
vector<pair<int, int>> grounds;
36+
while(!q.empty()) {
37+
auto [x,y] = q.front(); q.pop();
38+
num[x][y] = islands.size();
39+
grounds.emplace_back(x,y);
40+
for(int k=0;k<4;k++) {
41+
int xx = x+dx[k], yy = y+dy[k];
42+
if(xx<0 || xx>=W || yy<0 || yy>=H || arr[xx][yy] != 'X' || vis[xx][yy]) continue;
43+
vis[xx][yy] = 1;
44+
q.emplace(xx,yy);
45+
}
46+
}
47+
islands.push_back(grounds);
48+
}
49+
50+
N = islands.size();
51+
if(N == 1) return cout<<0, 0;
52+
for(int i=0;i<N;i++) for(int j=0;j<N;j++) cost[i][j] = INF;
53+
54+
for(int i=0;i<N;i++) {
55+
for(int i=0;i<W;i++) for(int j=0;j<H;j++) vis[i][j] = 0;
56+
57+
queue<tuple<int, int, int>> q;
58+
for(auto [x,y] : islands[i]) {
59+
q.emplace(x,y,0);
60+
vis[x][y] = 1;
61+
}
62+
while(!q.empty()) {
63+
auto [x,y,d] = q.front(); q.pop();
64+
for(int k=0;k<4;k++) {
65+
int xx = x+dx[k], yy = y+dy[k];
66+
if(xx<0 || xx>=W || yy<0 || yy>=H || arr[xx][yy] == '.' || vis[xx][yy]) continue;
67+
if(arr[xx][yy] == 'X') {
68+
if(num[xx][yy] == num[x][y]) continue;
69+
int a = num[xx][yy];
70+
cost[a][i] = min(cost[a][i], d);
71+
cost[i][a] = min(cost[i][a], d);
72+
}
73+
else {
74+
q.emplace(xx,yy,d+1);
75+
vis[xx][yy] = 1;
76+
}
77+
}
78+
}
79+
}
80+
81+
for(int i=0;i<N;i++) for(int j=0;j<N;j++) for(int k=0;k<N;k++) cost[j][k] = min(cost[j][k], cost[j][i] + cost[i][k]);
82+
83+
for(int i=0;i<N;i++) {
84+
for(int j=0;j<(1<<N);j++) dp[i][j] = INF;
85+
dp[i][1<<i] = 0;
86+
}
87+
88+
int ans = INF;
89+
for(int i=0;i<N;i++) ans = min(ans, get(i,(1<<N)-1));
90+
cout<<ans;
91+
92+
}
93+
```

0 commit comments

Comments
 (0)