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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <bits/stdc++.h>
#define MAX_N 101 #define ll long long #define pll pair<ll, ll> #define all(a) begin(a), end(a) using namespace std;
ll n, m, cc, pc; ll match[MAX_N], seen[MAX_N], a[MAX_N];
ll id[MAX_N][MAX_N]; ll dis[MAX_N][MAX_N]; string pkl[MAX_N];
void bfs(ll cy, ll cx, ll ck) { queue<pll> q; bool vis[MAX_N][MAX_N]; memset(vis, false, sizeof(vis)); q.push({cy,cx}); ll dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}, d = 1; vis[cy][cx] = true; while(!q.empty()) { ll sz = q.size(); while(sz--) { auto [y, x] = q.front(); q.pop(); for(ll i = 0; i < 4; i++) { ll ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx] and pkl[ny][nx] != 'X') { vis[ny][nx] = true; q.push({ny,nx}); dis[ck][id[ny][nx]] = d; } } } d++; } }
void init() { for(ll i = 0; i < n; i++) for(ll j = 0; j < m; j++) if(pkl[i][j] == 'P') id[i][j] = ++pc;
for(ll i = 0; i < n; i++) for(ll j = 0; j < m; j++) if(pkl[i][j] == 'C') bfs(i,j,++cc); }
ll dfs(ll u, ll s, ll t) { for(ll i = 1; i <= pc; i++) { if(seen[i] == s or dis[u][i] > t) continue; seen[i] = s; if(match[i] == -1 or dfs(match[i], s, t)) { match[i] = u; return 1; } } return 0; }
ll biMatch(ll t) { ll res = 0; for(ll i = 1; i <= cc; i++) { if(dfs(i,i,t)) res++; } return res; }
ll solve() { if(!cc) return 0; if(cc > pc) return -1; for(ll i = 1; i <= cc; i++) for(ll j = 1; j <= pc; j++) if(!dis[i][j]) dis[i][j] = INT_MAX;
ll l = 1, r = INT_MAX, res = INT_MAX; while(l <= r) { ll m = l + (r - l) / 2;
memset(match, -1, sizeof(match)); memset(seen, -1, sizeof(seen));
ll ma = biMatch(m);
if(ma == cc) { res = m; r = m - 1; } else l = m + 1; }
return res == INT_MAX ? -1 : res; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>m; for(ll i = 0; i < n; i++) cin>>pkl[i]; init(); cout<<solve(); return 0; }
|