好奇怪有一个wa了这是为什么
查看原帖
好奇怪有一个wa了这是为什么
1217917
AAAABCDDD楼主2025/1/27 10:57
//P2658 汽车拉力比赛
// 运用了二分和bfs
//二分答案看哪个答案满足条件就用哪个结果 最大里找最小的二分模型


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int N = 510;
int n, m;
int high[N][N];
int flag[N][N];
int dist[N][N];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
typedef pair<int, int> PII;
queue<PII> q;
int cnt;
PII start;

bool bfs(int x, int y, int h) {
	int cnt_1 = 1;
	memset(dist, -1, sizeof(dist));
	dist[x][y] = 0;
	q.push({x, y});
	
	while (!q.empty()) {
		PII t = q.front();
		q.pop();
		
		for (int i = 0; i < 4; ++i) {
			int tx = t.first + dx[i], ty = t.second + dy[i];
			if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
			if (dist[tx][ty] >= 0) continue;
			if (abs(high[tx][ty] - high[t.first][t.second]) > h) continue;
			dist[tx][ty] = dist[t.first][t.second] + 1;
			if (flag[tx][ty] == 1)cnt_1 += 1;
			q.push({tx, ty});
			//if (cnt == cnt_1) return true; // if搁到这就错一个
		}
	}
	//if (cnt == cnt_1) return true; //if搁到这就都对 
	return false;
}

bool check(int h) {
    bool res = bfs(start.first, start.second, h);
    return res;
  
}

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= m; ++j) {
			scanf("%d", &high[i][j]);
		}
	}
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= m; ++j) {
			scanf("%d", &flag[i][j]);
			if (flag[i][j] == 1) {
			    cnt++;
			    start = {i, j};
			}
		}
	}
	int l = -1, r = 1e9 + 1;
	while(l + 1 < r) {
		int mid = (l + r) / 2;
		if (check(mid)) r = mid;
		else l = mid;
	}
    printf("%d\n", r);
	return 0;
}
2025/1/27 10:57
加载中...