Cod sursa(job #2610197)

Utilizator CristiPopaCristi Popa CristiPopa Data 4 mai 2020 17:02:52
Problema Diametrul unui arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100009

vector<pair<int, int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
const int kMax = 300;

class Task {
 public:
    void solve() {
        read_input();
        get_result();
        print_output();
    }

 private:
    int n;
    char matrix[kMax][kMax];
    int minDist[kMax][kMax];
    queue<pair<int, int>> q;

    void read_input() {
        ifstream fin("muzeu.in");
        fin >> n;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                fin >>matrix[i][j];
                switch(matrix[i][j]) {
                    case 'P':
                        q.push({i, j});
                        minDist[i][j] = 0;
                        break;
                    case '#':
                        minDist[i][j] = -2;
                        break;
                    default:
                        minDist[i][j] = INT_MAX;
                        break;
                }
            }
        }
        fin.close();
    }

    void get_result() {
        while (!q.empty()) {
            pair<int, int> curr = q.front();
            q.pop();
            int d = minDist[curr.first][curr.second];
            for (auto &dir : directions) {
                int tarX = curr.first + dir.first;
                int tarY = curr.second + dir.second;
                if (inMuseum(tarX, tarY) && minDist[tarX][tarY] > d + 1) {
                    minDist[tarX][tarY] = d + 1;
                    q.push({tarX, tarY});
                }
            }
        }
    }

    bool inMuseum(int x, int y) {
        return x >= 0 && y >= 0 && x < n && y < n;
    }
    void print_output() {
        ofstream fout("muzeu.out");
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                fout << (minDist[i][j] == INT_MAX ? -1 : minDist[i][j]) << ' ';
            }
            fout << endl;
        }
        fout.close();
    }
};

// Please always keep this simple main function!
int main() {
    // Allocate a Task object on heap in order to be able to
    // declare huge static-allocated data structures inside the class.
    Task *task = new Task();
    task->solve();
    delete task;
    return 0;
}