L i n k Link Link
l u o g u T 145195 luogu\ T145195 luogu T145195
D e s c r i p t i o n Description Description
I n p u t Input Input
O u t p u t Output Output
S a m p l e Sample Sample I n p u t Input Input
4 4
.#.C
.#.#
....
S...
S a m p l e Sample Sample O u t p u t Output Output
4
H i n t Hint Hint
S o l u t i o n Solution Solution
先
d
f
s
dfs
dfs?建图,上下左右一个点各连一条边(当然是没有墙的情况),然后考虑传送门,我们四个方向一直走,直至撞墙或者是走到边界(要记忆化搜索, 否则TLE),边权就是到四方向的终点中所走空格最少的路径长度
然后SPFA
神仙题目,改了我三个多小时
C o d e Code Code
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char cc;
int t, r, c, S, T;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int dis[1000005], h[1000005], vis[1000005];
int a[1001][1001], ac[1005][1005], re[4][10000005], get[4], end[4][1000005];
struct node
{
int to, next, val;
}w[8000005];
void add(int x, int y, int z)
{w[++t] = (node){y, h[x], z}; h[x] = t;}
bool check(int x, int y)
{
if (x < 1 || x > r || y < 1 || y > c) return 0;
return 1;
}
void spfa(int s)
{
memset(dis, 0x3f, sizeof(dis));
vis[s] = 1;
dis[s] = 0;
queue<int>Q;
Q.push(s);
while(Q.size())
{
int tot = Q.front();
Q.pop();
for (int i = h[tot]; i; i = w[i].next)
{
int to = w[i].to;
if (dis[to] > dis[tot] + w[i].val)
{
dis[to] = dis[tot] + w[i].val;
if (!vis[to])
{
vis[to] = 1;
Q.push(to);
}
}
}
vis[tot] = 0;
}
}//spfa
int dfs(int x, int y, int pla)
{
if (a[x][y] || !check(x, y)) {
get[pla] = ac[x - dx[pla]][y - dy[pla]];
end[pla][ac[x][y]] = get[pla];
return re[pla][ac[x][y]] = 0;
}//撞墙了或越界的情况
if (re[pla][ac[x][y]]) {
get[pla] = end[pla][ac[x][y]];
return re[pla][ac[x][y]];
}//已经到过了
int rr = dfs(x + dx[pla], y + dy[pla], pla) + 1;
end[pla][ac[x][y]] = end[pla][ac[x + dx[pla]][y + dy[pla]]];
return re[pla][ac[x][y]] = rr;
}
int main()
{
scanf("%d%d", &r, &c);
for (int i = 1; i <= r; ++i)
{
for (int j = 1; j <= c; ++j)
{
cc = getchar();
while (cc != '#' && cc != 'S' && cc != 'C' && cc != '.')
cc = getchar();
if (cc == '#') a[i][j] = 1;
if (cc == 'S') S = (i - 1) * c + j;
if (cc == 'C') T = (i - 1) * c + j;
ac[i][j] = (i - 1) * c + j;
}
}
for (int i = 1; i <= r; ++i)
for (int j = 1; j <= c; ++j) {
if (!a[i][j]) {
int start = ac[i][j], sp = 2147483647;
for (int k = 0; k < 4; ++k)
{
int xx = i + dx[k];
int yy = j + dy[k];
sp = min(sp, dfs(xx, yy, k) + 1);
if (!a[xx][yy] && check(xx, yy)) add(ac[i][j], ac[xx][yy], 1);//先向四个点连个边
}
for (int k = 0; k < 4; ++k)
if (start != get[k])
add(start, get[k], sp);
}
}
spfa(S);
printf("%d", dis[T]);
}