はまやんはまやんはまやん

hamayanhamayan's blog

最も海から遠い場所 [yukicoder 402]

問題

http://yukicoder.me/problems/no/402

縦H×横Wの地図がある。
地図には陸地(#)か海(.)かが書いてある。
地図外の領域はすべて海。
海からのチェビシェフ距離が最も遠い場所のその距離を求めてください。

1 <= H,W <= 3*10^3

考察

1. 最初はBFSゲーかと思ったが違った(違ってないけど)
2. 全ての地点の海からの最短チェビシェフ距離を求めて、その最大値を求めた
3. ダイクストラで計算していけば間に合う
4. (考察書いてるうちに嘘解答だと気づいた)
5. 単一始点ではないのですが、まず、海を距離0として、そこを始点としてプライオリティキューに全部突っ込む
6. そこからダイクストラ(実際BFSとあまり変わらないか)

実装

http://yukicoder.me/submissions/106538

typedef long long ll;
int H, W;
string S[3010];
//-----------------------------------------------------------------
struct Comp {
	bool operator() (pair<int, ll> a, pair<int, ll> b) {
		return a.second > b.second;
	}
};
#define INF INT_MAX/2
int dx[8] = { 0,1,1,1,0,-1,-1,-1 };
int dy[8] = { -1,-1,0,1,1,1,0,-1 };
bool done[3010][3010];
ll dist[3010][3010];
ll solve() {
	priority_queue<pair<int, ll>, vector<pair<int, ll> >, Comp> que;

	rep(y, 0, H) rep(x, 0, W) dist[y][x] = INF;

	rep(y, 0, H) rep(x, 0, W) {
		if ((x != 0 && x != W - 1) && (y != 0 && y != H - 1)) continue;

		if (S[y][x] == '#') {
			dist[y][x] = 1;
			done[y][x] = true;
			que.push(make_pair(y * 10000 + x, 1));
		}
	}

	rep(y, 0, H) rep(x, 0, W) if(S[y][x] == '.'){
		dist[y][x] = 0;
		done[y][x] = true;
		que.push(make_pair(y * 10000 + x, 0));
	}

	while (!que.empty()) {
		auto q = que.top(); que.pop();

		int x = q.first % 10000;
		int y = q.first / 10000;
		ll c = q.second;

		rep(i, 0, 8) {
			int yy = y + dy[i];
			int xx = x + dx[i];
			if (yy < 0 || H <= yy) continue;
			if (xx < 0 || W <= xx) continue;
			if (done[yy][xx]) continue;

			int cc = c + 1;

			if (S[yy][xx] == '.') cc = 0;

			if (cc < dist[yy][xx]) {
				dist[yy][xx] = cc;
				done[yy][xx] = true;
				que.push(make_pair(yy * 10000 + xx, cc));
			}
		}
	}

	ll ans = 0;
	rep(y, 0, H) rep(x, 0, W) ans = max(ans, dist[y][x]);
	return ans;
}
//-----------------------------------------------------------------
int main()
{
	cin >> H >> W;
	rep(y, 0, H) cin >> S[y];

	cout << solve() << endl;
}