本题数据可能过水,我暴力bfs,o(qn4) 卡过去了,但是在本机上测试极限数据跑到 3 秒左右。
数据生成器:
#include<bits/stdc++.h>
using namespace std;
//mt19937_64 gen(time(0));
int vis[50][50];
int randlr(int l, int r){
return rand() % (r - l + 1) + l;
}
int main(){
srand(time(0));
int n = 30, m = 30, q = 500;
cout << n << ' ' << m << ' ' << q << endl;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
vis[i][j] = randlr(1, 10) > 1;
cout << vis[i][j] << ' ';
}
cout << endl;
}
while(q--){
int ex, ey, sx, sy, tx, ty;
ex = randlr(1, n), ey = randlr(1, m);
while(!vis[ex][ey]) ex = randlr(1, n), ey = randlr(1, m);
sx = randlr(1, n), sy = randlr(1, m);
while(!vis[sx][sy] || (sx == ex && sy == ey)) sx = randlr(1, n), sy = randlr(1, m);
tx = randlr(1, n), ty = randlr(1, m);
while(!vis[tx][ty]) tx = randlr(1, n), ty = randlr(1, m);
cout << ex << ' ' << ey << ' ' << sx << ' ' << sy << ' ' << tx << ' ' << ty << endl;
}
return 0;
}
暴力代码:
int n, m, q;
int g[N][N];
int d[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
//int f[N][N][N][N]; // f(i,j,k,t) 从初始状态到 (空格在(i,j),指定点在(k,t)) 的最小步数
struct ti5 {int ex, ey, sx, sy, step;};
ti5 que[N * N * N * N];
int hd, tl;
bool vis[N][N][N][N];
void Solve(){
cin >> n >> m >> q;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> g[i][j];
}
}
int ex, ey, sx, sy, tx, ty;
while(q--){
memset(vis, 0, sizeof(vis));
cin >> ex >> ey >> sx >> sy >> tx >> ty;
//f[ex][ey][sx][sy] = 0;
hd = 1, tl = 0;
que[++tl] = (ti5){ex, ey, sx, sy, 0};
vis[ex][ey][sx][sy] = 1;
int ans = -1;
while(hd <= tl){
ti5 tmp = que[hd];
hd++;
if(tmp.sx == tx && tmp.sy == ty){
ans = tmp.step;
break;
}
for(register int i = 0; i < 4; i++){
int xx = tmp.ex + d[i][0], yy = tmp.ey + d[i][1];
if(xx < 1 || xx > n || yy < 1 || yy > m || g[xx][yy] == 0) continue;
if(xx == tmp.sx && yy == tmp.sy){
if(!vis[xx][yy][tmp.ex][tmp.ey]){
que[++tl] = (ti5){xx, yy, tmp.ex, tmp.ey, tmp.step + 1};
vis[xx][yy][tmp.ex][tmp.ey] = 1;
}
}else{
if(!vis[xx][yy][tmp.sx][tmp.sy]){
que[++tl] = (ti5){xx, yy, tmp.sx, tmp.sy, tmp.step + 1};
vis[xx][yy][tmp.sx][tmp.sy] = 1;
}
}
}
}
cout << ans << endl;
}
}