为什么有WA和TLE,调了好久...
  • 板块P1141 01迷宫
  • 楼主yandi_
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/9 17:55
  • 上次更新2024/8/9 19:24:09
查看原帖
为什么有WA和TLE,调了好久...
1187324
yandi_楼主2024/8/9 17:55
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
int n;
int m;
int dp[1001][1001];
int migong[1001][1001];
struct node{
	int x,y;
	node operator+ (const node S)const{
		node ans={x+S.x,y+S.y};
		return ans;
	}
};
node fangxiang[5]={{0,0},{0,-1},{0,1},{1,0},{-1,0}};
int bfs(int x,int y){
	queue<node> q;
	queue<node> ue;
	q.push({x,y});
	int ans=0;
	bool went[n+1][n+1]={};
	while(!q.empty()){
		node now=q.front();
		q.pop();
		ue.push(now);
		for(int i=1;i<=4;i++){
			node will=now+fangxiang[i];
			if(will.x>0 && will.x<=n && will.y>0 && will.y<=n && migong[will.x][will.y]==!migong[now.x][now.y] && !went[will.x][will.y]){
				ans++;
				q.push(will);
				went[will.x][will.y]=1;
			}
		}
	}
	//cout<<ans<<endl;
	while(ue.size()){
		node now1=ue.front();
		ue.pop();
		dp[now1.x][now1.y]=ans;
	}
	return dp[x][y];
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			scanf("%1d",&migong[i][j]);
		}
	}
	for(int i=1;i<=m;i++){
		int a,b;
		cin>>a>>b;
		if(dp[a][b]){
			cout<<dp[a][b]<<endl;
			continue;
		}
		cout<<bfs(a,b)<<endl;
	}
	return 0;
}
2024/8/9 17:55
加载中...