Pagini recente » Cod sursa (job #129584) | Cod sursa (job #1418068) | Cod sursa (job #1329513) | Cod sursa (job #2151438) | Cod sursa (job #3224008)
#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';
}
}