Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- #include <set>
- #include <cstring>
- using namespace std;
- const int maxn = 55;
- int n, m;
- char mat[maxn][maxn];
- int dist[maxn][maxn][maxn][maxn];
- bool visited[maxn][maxn];
- vector<pair<int, int> > tables, customers;
- void bfs(int si, int sj) {
- memset(visited, false, sizeof visited);
- visited[si][sj] = true;
- queue<int> Q;
- Q.push(si);
- Q.push(sj);
- Q.push(0);
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1, 1};
- while(!Q.empty()) {
- int ci = Q.front();
- Q.pop();
- int cj = Q.front();
- Q.pop();
- int d = Q.front();
- Q.pop();
- if(mat[ci][cj] == 'M') {
- dist[si][sj][ci][cj] = d;
- }
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and mat[ti][tj] != '#') {
- Q.push(ti);
- Q.push(tj);
- Q.push(d + 1);
- visited[ti][tj] = true;
- }
- }
- }
- }
- int graph[111][111];
- int match[111];
- bool vis[111];
- bool dfs(int node) {
- for(int i = 0; i < tables.size(); i++) {
- if(graph[node][i] == 1 and !vis[i]) {
- vis[i] = true;
- if(match[i] == -1 or dfs(match[i])) {
- match[i] = node;
- return true;
- }
- }
- }
- return false;
- }
- bool check(int distance) {
- memset(graph, 0, sizeof graph);
- for(int i = 0; i < customers.size(); i++) {
- for(int j = 0; j < tables.size(); j++) {
- if(dist[customers[i].first][customers[i].second][tables[j].first][tables[j].second] <= distance) {
- graph[i][j] = 1;
- }
- }
- }
- memset(match, -1, sizeof match);
- int matched = 0;
- for(int i = 0; i < customers.size(); i++) {
- memset(vis, false, sizeof vis);
- if(dfs(i)) {
- matched++;
- }
- }
- return (matched >= (int) customers.size());
- }
- int main()
- {
- cin >> n >> m;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- }
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- for(int x = 0; x < n; x++) {
- for(int y = 0; y < m; y++) {
- dist[i][j][x][y] = 2e9;
- }
- }
- }
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(mat[i][j] == 'P') {
- bfs(i, j);
- customers.push_back(make_pair(i, j));
- }
- if(mat[i][j] == 'M') {
- tables.push_back(make_pair(i, j));
- }
- }
- }
- int L = 0, R = 3333;
- int result = 2e9;
- while(L <= R) {
- int middle = (L + R) / 2;
- if(check(middle)) {
- result = min(result, middle);
- R = middle - 1;
- }
- else {
- L = middle + 1;
- }
- }
- cout << result << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement