1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <vector> #include <unordered_map>
using namespace std;
int apartmentHunting(vector<unordered_map<string, bool>> blocks, vector<string> reqs) { int mi = INT_MAX, n = blocks.size(), id = 0, res = -1; unordered_map<string, int> idmp; vector<vector<int>> left(n, vector<int>(reqs.size(), n + 1)); vector<vector<int>> right(n, vector<int>(reqs.size(), n + 1));
for(auto& req : reqs) idmp[req] = id++;
for(int i = 0; i < n; i++) { for(auto& [building, placedAt] : blocks[i]) { if(!idmp.count(building)) continue; int id = idmp[building];
if(placedAt) left[i][id] = 0; else left[i][id] = (i ? left[i-1][id] + 1 : n + 1); } }
for(int i = n - 1; i >= 0; i--) { for(auto& [building, placedAt] : blocks[i]) { if(!idmp.count(building)) continue; int id = idmp[building];
if(placedAt) right[i][id] = 0; else right[i][id] = (i != n - 1 ? right[i+1][id] + 1 : n + 1); }
int distance = 0;
for(int j = 0; j < id; j++) { distance = max(distance, min(left[i][j], right[i][j])); }
if(mi > distance) { mi = distance; res = i; } }
return res; }
|