https://www.luogu.org/problemnew/show/P1606
这是 dy0607 d y 0607 讲课的题目..当时觉得这个题挺简单打实际上还是蛮多坑点
首先你直接建出图后会发现最短路是对的但是方案数是错的
因为有荷叶的存在图中存在很多0边
那么怎么办呢 既然是荷叶的锅不要荷叶不就得了
每个点对于它能一步到达的所有点连边 通过
BFS
B
F
S
完成
直接跑最短路计数即可
那么复杂度瓶颈就在建边上了 O(n2m2) O ( n 2 m 2 )
Codes
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 33, M = 2e6 + 10;
int fx[8][2] = {{2, 1}, {2, -1}, {-1, 2}, {-1, -2}, {1, 2}, {1, -2}, {-2, 1}, {-2, -1}};
int to[M], head[M], nxt[M], v[M], e;
int n, m, s, t, a[N][N];
int id(int x, int y) {
return (x - 1) * m + y;
}
void add(int x, int y, int z) {
to[++ e] = y; nxt[e] = head[x]; head[x] = e; v[e] = z;
}
void bfs(int u) {
int vis[N * N] = {0};
queue<int> q;
vis[u] = 1, q.push(u);
while(!q.empty()) {
int k = q.front(); q.pop();
int x = (k - 1) / m + 1, y = (k - 1) % m + 1;
for(int i = 0; i < 8; ++ i) {
int xx = x + fx[i][0], yy = y + fx[i][1];
if(xx < 1 || xx > n || yy < 1 || yy > m || vis[id(xx, yy)]) continue;
if(a[xx][yy] == 0 || a[xx][yy] == 4) add(u, id(xx, yy), 1);
if(a[xx][yy] == 1) q.push(id(xx, yy));
vis[id(xx, yy)] = 1;
}
}
}
void SPFA() {
queue<int> q;
int dis[N * N] = {0}, cnt[N * N] = {0}, vis[N * N] = {0};
for(int i = 1; i <= n * m; ++ i) dis[i] = 1e18;
cnt[s] = 1, dis[s] = 0, vis[s] = 1; q.push(s);
while(!q.empty()) {
int x = q.front(); q.pop();
for(int i = head[x]; i; i = nxt[i]) {
if(dis[to[i]] > dis[x] + v[i]) {
dis[to[i]] = dis[x] + v[i];
cnt[to[i]] = 0;
if(!vis[to[i]])
vis[to[i]] = 1, q.push(to[i]);
}
if(dis[to[i]] == dis[x] + v[i])
cnt[to[i]] += cnt[x];
}
vis[x] = 0;
}
if(dis[t] == 1e18) return void(printf("-1\n"));
printf("%lld\n%lld\n", dis[t] - 1, cnt[t]);
// for(int i = 1; i <= n; ++ i)
// for(int j = 1; j <= m; ++ j)
// printf("%d %d %d\n", i, j, dis[id(i, j)]);
}
signed main() {
#ifndef ONLINE_JUDGE
freopen("1606.in", "r", stdin);
freopen("1606.out", "w", stdout);
#endif
scanf("%lld%lld", &n, &m);
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= m; ++ j) {
scanf("%lld", &a[i][j]);
if(a[i][j] == 3) s = id(i, j);
if(a[i][j] == 4) t = id(i, j);
}
bfs(s);
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= m; ++ j)
if(a[i][j] == 0)
bfs(id(i, j));
SPFA();
return 0;
}