社区讨论

P9065云梦谣,75分,求大佬调

灌水区参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@m2ekr048
此快照首次捕获于
2024/10/18 18:15
去年
此快照最后确认于
2025/11/04 16:55
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3 * 1e3 + 1000;
int n,m,k,ans = INT_MAX,ans2,bfs1_num,flag = -1,flag1 = -1;
int mapp[maxn][maxn],ans_bfs1[maxn][maxn],ans_bfs2[maxn][maxn];
bool vis[maxn][maxn],tp[maxn][maxn];
int dirx[5] = {1,0,-1,0},diry[5] = {0,1,0,-1};
vector <int> start;
vector <int> endn;
queue <pair<int,int> > q;
queue <pair<int,int> > q2;
void bfs1(){
	q.push({1,1});
	vis[1][1] = 1;
	while(!q.empty()){
		pair <int,int> now = q.front();
		if(now.first == n && now.second == m) return;
		q.pop();
		for(int i = 0;i <= 3;i++){
			int tx = now.first + dirx[i];
			int ty = now.second + diry[i];
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && mapp[tx][ty] != 0 && vis[tx][ty] != 1){
				ans_bfs1[tx][ty] = ans_bfs1[now.first][now.second] + 1;
				vis[tx][ty] = 1;
				if(tp[tx][ty]){
					if(flag == -1){
						flag = ans_bfs1[tx][ty];
						start.push_back(mapp[tx][ty]);
					}else if(flag == ans_bfs1[tx][ty]){
						start.push_back(mapp[tx][ty]);
					}
				}
				q.push({tx,ty});
			}
		}
	}
}
void bfs2(){
	memset(vis,0,sizeof(vis));
	q2.push({n,m});
	vis[n][m] = 1;
	while(!q2.empty()){
		pair <int,int> now = q2.front();
		if(now.first == 1 && now.second == 1) return;
		q2.pop();
		for(int i = 0;i <= 3;i++){
			int tx = now.first + dirx[i];
			int ty = now.second + diry[i];
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && mapp[tx][ty] != 0 && vis[tx][ty] != 1){
				ans_bfs2[tx][ty] = ans_bfs2[now.first][now.second] + 1;
				vis[tx][ty] = 1;
				q2.push({tx,ty});
				if(tp[tx][ty]){
					if(flag1 == -1){
						//cout << "ok" << endl;
						flag1 = ans_bfs2[tx][ty];
						endn.push_back(mapp[tx][ty]);
						//cout << "flag1:"<< flag1 << endl;
					}else if(flag1 == ans_bfs1[tx][ty]){
						endn.push_back(mapp[tx][ty]);
					}
				}
				//cout << "x:" << tx << " " <<"y="<< ty << endl;
				
			}
		}
		
		
	}
	if(flag1 != -1) return;
}
int main(){
	cin >> n >> m >> k;
	for(int i = 1;i <= n;i++)
		for(int j = 1;j <= m;j++)
			cin >> mapp[i][j];
	for(int i = 1;i <= k;i++){
		int x,y;
		cin >> x >> y;
		tp[x][y] = 1;
	}
	if(tp[1][1] == 1){
		start.push_back(mapp[1][1]);
		flag = 0;
	}
	if(tp[n][m] == 1){
		endn.push_back(mapp[n][m]);
		flag = 0;
	}
	bfs1();
	if(ans_bfs1[n][m] != 0) ans = ans_bfs1[n][m];
	bfs2();
	for(auto i : start){
		for(auto j : endn){
			if(i != j) ans = min(ans,flag1 + flag + 2);
			else ans = min(ans,flag1 + flag + 1);
		}
	}
	if(ans == INT_MAX) cout << -1;
	else cout << ans;
	return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...