70分,TLE,蒟蒻求助
查看原帖
70分,TLE,蒟蒻求助
910040
xiexiaoyuawa楼主2024/4/8 12:32

bfs写的, #1 #6 #7 #11 TLE

#include <iostream>
#include <queue>

using namespace std;

const int maxn = 1010;
int n, m;
char a[maxn][maxn];
bool vis[maxn][maxn];
struct coord{
	int x, y;
};
queue <coord> q;
const int dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int ans;

bool match(coord node1, coord node2){
	if(a[node1.y][node1.x] == '1' && a[node2.y][node2.x] == '0') return 1;
	if(a[node1.y][node1.x] == '0' && a[node2.y][node2.x] == '1') return 1;
	return 0;
}

int main(){
	cin >> n >> m;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++){
			cin >> a[i][j];
		}
	}
	while(m--){
		ans = 1;
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){
				vis[i][j] = 0;
			}
		}
		int ii, jj;
		cin >> ii >> jj;
		ii--, jj--;
		vis[ii][jj] = 1;
		coord node;
		node.x = jj, node.y = ii;
		q.push(node);
		while(!q.empty()){
			coord now = q.front();
			q.pop();
			for(int i = 0; i < 4; i++){
				int nextx = now.x + dirs[i][0];
				int nexty = now.y + dirs[i][1];
				if(nextx >= 0 && nexty >= 0 && nextx < n && nexty < n){
					if(!vis[nexty][nextx] && match(now, (coord){nextx, nexty})){
						vis[nexty][nextx] = 1;
						q.push((coord){nextx, nexty});
						ans++;
					}
				}
			}
		}
		cout << ans << '\n';
	}
	return 0;
}
2024/4/8 12:32
加载中...