Cod sursa(job #3224008)

Utilizator RobertAcAcatrinei Robert-Marian RobertAc Data 14 aprilie 2024 12:31:57
Problema Obiective Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.28 kb
#include <bits/stdc++.h>
#ifdef LOCAL
#define in cin
#define out cout
#endif

using namespace std;

#ifndef LOCAL
ifstream in("obiective.in");
ofstream out("obiective.out");
#endif

const int nmax = 32005;

vector<int> adj[nmax];
vector<int> revadj[nmax];
bool viz[nmax];

int bfs(int start, int target)
{
    deque<pair<int, int>> dq;
    memset(viz, 0, sizeof viz);
    dq.push_back({start, 0});
    while (!dq.empty())
    {
        auto nod = dq.front();
        dq.pop_front();
        if (viz[nod.first])
            continue;
        viz[nod.first] = 1;
        if (nod.first == target)
        {
            return nod.second;
        }
        for (auto i : adj[nod.first])
        {
            if (!viz[i])
            {
                dq.push_front({i, nod.second});
            }
        }
        for (auto i : revadj[nod.first])
        {
            if (!viz[i])
            {
                dq.push_back({i, nod.second + 1});
            }
        }
    }
}

int main()
{
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        in >> a >> b;
        adj[a].push_back(b);
        revadj[b].push_back(a);
    }
    int q;
    in >> q;
    for (int i = 0; i < q; i++)
    {
        int a, b;
        in >> a >> b;
        out << bfs(a, b) << '\n';
    }
}