D 题 A* 求调
  • 板块题目总版
  • 楼主ny_Dacong
  • 当前回复10
  • 已保存回复10
  • 发布时间2025/1/4 21:40
  • 上次更新2025/1/5 09:52:19
查看原帖
D 题 A* 求调
928972
ny_Dacong楼主2025/1/4 21:40

样例三输出 160.

#include<bits/stdc++.h>
using namespace std;
int n,m;
int SX,SY,EX,EY;
bool Map[1050][1050];
int Min[1050][1050][2];
struct node{
	int xp,yp,Step,Last;
};
bool operator<(node x,node y){
	return x.Step+abs(x.xp-EX)+abs(x.yp-EY) < y.Step+abs(y.xp-EX)+abs(y.yp-EY);
}
priority_queue<node> que;
int a_star(){
	que.push({SX,SY,0,0});
	que.push({SX,SY,0,1});
	node now,Next;
	while(que.size()){
		now = que.top();
		que.pop();
//		printf("%d %d %d %d\n",now.xp,now.yp,now.Step,now.Last);
		Min[now.xp][now.yp][now.Last] = min(now.Step,Min[now.xp][now.yp][now.Last]);
		if(now.xp == EX && now.yp == EY){
			return now.Step;
		}
		for(int i = -1; i <= 1; i++){
			if(i == 0){
				continue;
			}
			Next = now;
			if(now.Last){
				Next.xp += i;
			}else{
				Next.yp += i;
			}
			Next.Step++,Next.Last = !Next.Last;
			if(Next.xp < 1 || Next.yp < 1 || Next.xp > n || Next.yp > m || Map[Next.xp][Next.yp]){
				continue;
			}
			if(Next.Step > Min[Next.xp][Next.yp][Next.Last]){
				continue;
			}
			Min[Next.xp][Next.yp][Next.Last] = min(Min[Next.xp][Next.yp][Next.Last],Next.Step);
			que.push(Next);
		}
	}
	return -1;
}
int main(){
	scanf("%d%d",&n,&m);
	memset(Min,0x3f,sizeof(Min));
	for(int i = 1; i <= n; i++){
		static char tp;
		for(int j = 1; j <= m; j++){
			scanf(" %c",&tp);
			if(tp == 'S'){
				SX = i,SY = j;
			}else if(tp == 'G'){
				EX = i,EY = j;
			}else if(tp == '#'){
				Map[i][j] = 1;
			}else{
				Map[i][j] = 0;
			}
		}
	}
	printf("%d",a_star());
	return 0;
}
2025/1/4 21:40
加载中...