CF1301F - Super Jaber

一张图两种方式

  • 随便走一步
  • 跳到相同颜色的点

询问从$(x1,y1)\rightarrow (x2,y2)$最少步数。$n,m\leq 1000,c\leq 40$

从某个点到某个点,坑定是从某个颜色跳到某个颜色。暴力枚举所有颜色。

预处理出每种颜色到不同点的距离,因为求距离最小值,暴力$BFS$即可。
$O(cnm+qc)$

代码
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
  </details>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mk make_pair
const int N = 1e3 + 10;
const int mod = 1e9 + 7;
const int M = 45;
int dx[] = {0, 0, 1, -1};
int dy[] = {-1, 1, 0, 0};
int n, m;
int dis[M][N][N], vis[N][N], vc[M];
int k, c[N][N];
vector<pii> g[M];
void bfs(int col)
{
//cout << col << "----" << endl;
queue<pii> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
vis[i][j] = 0, dis[col][i][j] = 1e9;
for (int i = 1; i <= k; i++)
vc[i] = 0;
for (pii s : g[col])
{
dis[col][s.first][s.second] = 0;
vis[s.first][s.second] = 1;
q.push(s);
}

vc[col] = 1;
while (!q.empty())
{
pii now = q.front();
int x = now.first;
int y = now.second;
q.pop();
if (!vc[c[x][y]])
{

for (pii s : g[c[x][y]])
{
if (!vis[s.first][s.second])
{
dis[col][s.first][s.second] = min(dis[col][s.first][s.second], dis[col][x][y] + 1);
q.push(mk(s.first, s.second));
vis[s.first][s.second] = 1;
}
}
vc[c[x][y]] = 1;
}
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy])
{
dis[col][xx][yy] = min(dis[col][xx][yy], dis[col][x][y] + 1);
vis[xx][yy] = 1;
q.push(mk(xx, yy));
}
}
}
}

int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &c[i][j]);
g[c[i][j]].push_back(mk(i, j));
}
for (int i = 1; i <= k; i++)
bfs(i);
int q;
scanf("%d", &q);
for (int i = 1; i <= q; i++)
{
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
int ans = abs(x1 - x2) + abs(y1 - y2);
for (int j = 1; j <= k; j++)
ans = min(ans, dis[j][x1][y1] + dis[j][x2][y2] + 1);

printf("%d\n", ans);
}
}