B - Humidifier 2 Editorial by en_translator
If we put humidifiers to cell \((i_1,j_1)\) and \((i_2,j_2)\), a cell \((i,j)\) is humidified if and only if \(|i-i_1|+|j-j_1|\leq D\) or \(|i-i_2|+|j-j_2| \leq D\); this can be checked easily.
Thus, we can brute-force over the places to put the humidifiers, count how many cells are humidified for each placement by inspecting each cell, and find their maximum value.
There are at most \((HW)^2\) ways to put the humidifiers, and we need to inspect \(HW\) cells to check if it is humidified for each placement, so the overall complexity is \(\mathrm{O}((HW)^3)\).
Note that we can only place humidifiers onto a wall, and the sought value is the number of humidified wall cells.
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
int h, w, d;
cin >> h >> w >> d;
vector<string> s(h);
for (int i = 0; i < h; ++i) {
cin >> s[i];
}
int ans = 0;
for (int i1 = 0; i1 < h; ++i1) {
for (int j1 = 0; j1 < w; ++j1) {
if (s[i1][j1] == '#')
continue; // not a floor cell
for (int i2 = 0; i2 < h; ++i2) {
for (int j2 = 0; j2 < w; ++j2) {
if (s[i2][j2] == '#' || (i1 == i2 && j1 == j2))
continue; // non-floor cell, or coincides with one of the cells with humidifiers
int tmp = 0;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if (s[i][j] == '.' && (abs(i - i1) + abs(j - j1) <= d || abs(i - i2) + abs(j - j2) <= d)) {
tmp++; // humidified
}
}
}
ans = max(ans, tmp);
}
}
}
}
cout << ans << endl;
}
posted:
last update: