Cod sursa(job #2534640)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 30 ianuarie 2020 20:06:43
Problema Castel Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("castel.in");
ofstream g("castel.out");

int n, m, k, i, j;
int usa[151][151];
int cheie[151][151], c;
bool cheie_gasita[22501];
bool u[151][151], u1[22501];
int rez;

int dx[4] = {1, -1, 0,  0};
int dy[4] = {0,  0, 1, -1};

bool ok(int x, int y)
{
    return (x>=1 && x<=n && y>=1 && y<=m);
}

int main()
{
    f >> n >> m >> k;
    for (i=1; i<=n; i++)
        for (j=1; j<=m; j++)
        {
            f >> usa[i][j];
            cheie[i][j] = ++c;
        }

    int poz1 = k/m + (k%m > 0);
    int poz2 = k%m + m*(k%m == 0);

    int x, y;
    int xx, yy;
    bool gata=0;

    u[poz1][poz2] = 1;
    cheie_gasita[cheie[poz1][poz2]] = 1;

    queue < pair < int, int > > cu_cheie;
    vector < pair < int, int > > fara_cheie;
    cu_cheie.push(make_pair(poz1, poz2));

    while (!gata)
    {
        if (cu_cheie.empty())
            gata=1;
        else
            while (!cu_cheie.empty())
            {
                x = cu_cheie.front().first;
                y = cu_cheie.front().second;
                cu_cheie.pop();
                rez++;
                for (i=0; i<4; i++)
                {
                    xx = x + dx[i];
                    yy = y + dy[i];
                    if (ok(xx, yy) && !u[xx][yy])
                    {
                        u[xx][yy] = 1;
                        if (cheie_gasita[usa[xx][yy]])
                        {
                            cheie_gasita[cheie[xx][yy]] = 1;
                            cu_cheie.push(make_pair(xx, yy));
                        }
                        else
                            fara_cheie.push_back(make_pair(xx, yy));
                    }
                }
            }

        for (i=0; i<fara_cheie.size(); i++)
            if (!u1[i])
            {
                x = fara_cheie[i].first;
                y = fara_cheie[i].second;
                if (cheie_gasita[usa[x][y]])
                {
                    cu_cheie.push(make_pair(x, y));
                    cheie_gasita[cheie[x][y]] = 1;
                    u1[i] = 1;
                }
            }

    }

    g << rez;

    return 0;
}