Cod sursa(job #2728878)

Utilizator gasparrobert95Gaspar Robert Andrei gasparrobert95 Data 23 martie 2021 20:18:24
Problema Castel Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.44 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("castel.in");
ofstream fout("castel.out");
int n, m, k, rez, mt[155][155];
int ox[] = {-1, 0, 1, 0}, oy[] = {0, 1, 0, -1};
bool used[22505], avem[22505];
vector <int> v[22505];
queue <int> q;

pair <int, int> convert(int cod) {
    int x = cod / m, y = cod % m;
    if (cod % m != 0)
        ++x;
    if (y == 0)
        y = m;
    return {x, y};
}

int convert2(int x, int y) {
    return (x - 1) * m + y;
}

int main() {
    fin >> n >> m >> k;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j)
            fin >> mt[i][j];
    q.push(k);
    used[k] = true;
    while (!q.empty()) {
        int cod = q.front(), x = convert(cod).first, y = convert(cod).second;
        avem[cod] = true;
        ++rez;
        q.pop();
        for (int i = 0; i < v[cod].size(); ++i) {
            if (!used[v[cod][i]])
                q.push(v[cod][i]);
            used[v[cod][i]] = true;
        }
        v[cod].clear();
        for (int p = 0; p < 4; ++p) {
            int a = x + ox[p], b = y + oy[p];
            if (a < 1 || a > n || b < 1 || b > m)
                continue;
            int cod2 = convert2(a, b);
            if (!used[cod2] && avem[mt[a][b]])
                used[cod2] = true, q.push(cod2);
            else
                v[mt[a][b]].push_back(cod2);
        }
    }
    fout << rez;
    return 0;
}