[Nowcoder190H] CSL的校园卡

题目链接:https://www.nowcoder.com/acm/contest/190/H

中文题面不解释。

很容易想到dp,但是要仔细设计一下状态。

两个人一起走,可以直接定义状态为dp(ax,ay,bx,by),但是要维护每个可行点都遍历过,那么可以二进制位压。状态记成dp(sta,ax,ay,bx,by),然后常规dfs就行了。

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;

typedef struct Node {
int ax, ay, bx, by, st;
}Node;
const int maxn = 4;
const int dx[5] = {0, 0, 1, -1};
const int dy[5] = {1, -1, 0, 0};
int n, m, es;
char G[maxn][maxn];
int dp[1<<16][maxn][maxn][maxn][maxn];

inline int ok(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m && (G[x][y] == 'S' || G[x][y] == 'O');
}

inline int id(int x, int y) {
return x * m + y;
}

int bfs(int sx, int sy) {
memset(dp, -1, sizeof(dp));
queue<Node> q;
dp[1<<id(sx, sy)][sx][sy][sx][sy] = 0;
q.push({sx, sy, sx, sy, 1 << id(sx, sy)});
while(!q.empty()) {
Node t = q.front(); q.pop();
if(t.st == es) return dp[es][t.ax][t.ay][t.bx][t.by];
for(int i = 0; i < 4; i++) {
int ax = t.ax + dx[i], ay = t.ay + dy[i];
if(!ok(ax, ay)) continue;
for(int j = 0; j < 4; j++) {
int bx = t.bx + dx[j], by = t.by + dy[j];
if(!ok(bx, by)) continue;
int st = t.st | (1 << id(ax, ay));
st |= (1 << id(bx, by));
if(dp[st][ax][ay][bx][by] == -1) dp[st][ax][ay][bx][by] = dp[t.st][t.ax][t.ay][t.bx][t.by] + 1;
else continue;
q.push({ax, ay, bx, by, st});
}
}
}
return 0;
}

signed main() {
// freopen("in", "r", stdin);
while(~scanf("%d%d",&n,&m)) {
int x, y;
for(int i = 0; i < n; i++) {
scanf("%s", G[i]);
}
es = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(G[i][j] == 'O') es |= (1 << id(i, j));
if(G[i][j] == 'S') {
x = i, y = j;
es |= (1 << id(i, j));
}
}
}
printf("%d\n", bfs(x, y));
}
return 0;
}