Calcula el hoyo de la Copa Lanqiao

Participé en la competencia de simulación Blue Bridge Cup de Jie Suanke. Cuando resolví un problema de laberinto, primero usé dfs para hacerlo y se agotó el tiempo. Más tarde, recordé que este tipo de problema debería resolverse con bfs, y luego encontré un agujero al hacerlo. . . .

tema:

ingresar:

3 4
.. *.
.. *.
.. *.
2
2 2 2 4
3 1 1 4
3 4

Producción:

3

Idea de resolución de problemas: este problema se puede utilizar directamente para encontrar el camino más corto con bfs. A lo que hay que prestar atención es al foso del portal. En circunstancias normales, lo que consideramos es que un punto se transmite a otro punto. Sin embargo, el tipo de dato dado por la pregunta puede transmitirse de un punto a otro, y luego el punto al que se va a transmitir tiene un portal en sí mismo, y se volverá a transmitir.

Código AC:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1005;

int n, m, q, x, y, ans;
char G[maxn][maxn];
bool vis[maxn][maxn];
struct N{
	int x, y, step;
	N(int a, int b, int s):x(a), y(b), step(s){}
};
queue<N> Q;

struct D{
	int tx,ty;
}Tp[maxn][maxn];

int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

bool ok(int u, int v){
	if(u <= 0 || v <= 0 || u > n || v > m || G[u][v] == '*')return false;
	return true;
}

void bfs(int u, int v, int w){
	N tem = N(0, 0, 0);
	Q.push(N(u, v, w));
	vis[u][v] = true;
	while(!Q.empty()){
		tem = Q.front();
		Q.pop();
		if(tem.x == x && tem.y == y){
			ans = min(ans, tem.step);
		}
		while(Tp[tem.x][tem.y].tx != 0 && Tp[tem.x][tem.y].ty != 0 && G[Tp[tem.x][tem.y].tx][Tp[tem.x][tem.y].ty] != '*'){	
		//坑点,因为传送到某一点后,哪一点可能还有传送门,因此,必须循环 
			int x1 = tem.x, y1 = tem.y;
			tem.x = Tp[x1][y1].tx;
			tem.y = Tp[x1][y1].ty;
		}
		if(tem.x == x && tem.y == y){
			ans = min(ans, tem.step);
		}
		for(int i = 0; i < 4;i++){
			int nx = tem.x + dx[i];
			int ny = tem.y + dy[i];
			int nw = tem.step + 1;
			if(ok(nx, ny) && !vis[nx][ny]){
				vis[nx][ny] = true;
				Q.push(N(nx, ny, nw));
			}
		}
	}	
}

int main(){
	int a, b, c, d;
	while(scanf("%d%d", &n, &m) != EOF){
		memset(Tp, 0, sizeof Tp);
		memset(G, 0, sizeof G);
		memset(vis, false, sizeof vis);
		ans = 0x3f3f3f3f;
		while(!Q.empty())Q.pop();
		for(int i = 1; i <= n;i++){
			scanf("%s", G[i] + 1);//如果不加1则默认从下标0开始 
		}
		scanf("%d", &q);
		for(int i = 1; i <= q;i++){
			scanf("%d%d%d%d", &a, &b, &c, &d);
			Tp[a][b].tx = c;
			Tp[a][b].ty = d;
		}
		scanf("%d%d", &x, &y);//终点地方
		bfs(1, 1, 0);
		if(ans >= 0x3f3f3f3f / 2) 
			printf("No solution\n");
		else
			printf("%d\n", ans);
	}
	return 0;
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_40596572/article/details/104059244
Recomendado
Clasificación