17141号研究所2


97%で失敗しました...この時は反例だ.
5 2
1 1 1 1 1
1 1 2 1 1
1 1 2 1 1
1 1 1 1 1
1 1 1 1 1
このように、ウイルスが最初から拡散すると、時間はゼロ秒になります.そこで、BFSを回した後、distの最大値を求める.
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <tuple>
using namespace std;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int n, m;
vector<pair<int, int>> vir;
int bfs(vector<vector<int>>& map, queue<pair<int, int>>& Q) {
	int x, y;
	int dist[51][51];
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			dist[i][j] = -1;
		}
	}
	for (int i = 0; i < Q.size(); i++) {
		tie(x, y) = Q.front(); Q.pop();
		dist[x][y] = 0;
		Q.push(make_pair(x, y));
	}
	
	while (!Q.empty()) {
		tie(x, y) = Q.front(); Q.pop();
		for (int i = 0; i < 4; i++) {
			int xx = x + dx[i];
			int yy = y + dy[i];
			if (xx >= n || xx < 0 || yy >= n || yy < 0) continue;
			if (map[xx][yy] == 1) continue;
			if (dist[xx][yy] == -1) {
				dist[xx][yy] = dist[x][y] + 1;
				Q.push(make_pair(xx, yy));
			}
		}
	}
	int ans = -1;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] == 1) continue;
			if (dist[i][j] == -1) {
				return -1;
			}
			else if (ans < dist[i][j]) {
				ans = dist[i][j];
			}
		}
	}
	//cout << ans << '\n';
	return ans;
}
int main() {
	freopen("in1.txt", "rt", stdin);
	
	cin >> n >> m;
	vector<vector<int>> map(n, vector<int>(n));
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cin >> map[i][j];
			if (map[i][j] == 2) {
				vir.push_back(make_pair(i, j));
				//cout << i << " " << j << " " << '\n';
			}
		}
	}
	vector<int> comb;
	for (int i = 0; i < m; i++) {
		comb.push_back(1);
	}
	for (int i = 0; i < vir.size() - m; i++) {
		comb.push_back(0);
	}
	int ans = -1;
	sort(comb.begin(), comb.end());
	do {
		queue<pair<int, int>> Q;
		for (int i = 0; i < comb.size(); i++) {
			if (comb[i] == 1) {
				Q.push(make_pair(vir[i].first, vir[i].second));
				//cout << vir[i].first << " " << vir[i].second << " " << '\n';
			}
		}
		//cout << '\n';
		int tmp = bfs(map, Q);//bfs
		if (ans==-1||(tmp < ans&&tmp!=-1)) {
			ans = tmp;
			//cout << ans<< " "<<"tmp"<<tmp << '\n';
		}
	} while (next_permutation(comb.begin(), comb.end()));
	cout << ans << '\n';
	return 0;
}
参考資料
https://www.acmicpc.net/board/view/65077