Pagini recente » Cod sursa (job #2728952) | Cod sursa (job #3293112) | Cod sursa (job #3170024) | Cod sursa (job #3255670) | Cod sursa (job #3278747)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <math.h>
#include <algorithm>
#include <utility>
#define ll long long
#define pi pair<int, int>
#define ff first
#define ss second
#define pb push_back
#define all(v) v.begin(), v.end()
#define ushort unsigned short
#define inf 65535
#define debug(x) cout << #x << " = " << x << endl
using namespace std;
const string file = "obiective";
ifstream fin(file+".in");
ofstream fout(file+".out");
const int dim = 32005;
int n, m, a, b, i, j, q, comp[dim], viz[dim], nr;
vector<int> g[dim], gt[dim], f, sc[dim];
vector<pi> ng[dim];
map<pi, int> ma;
void dfs(int nod)
{
viz[nod] = 1;
for (auto x : g[nod])
if (!viz[x])
dfs(x);
f.pb(nod);
}
void dfs2(int nod, int nr)
{
comp[nod] = nr;
sc[nr].pb(nod);
for (auto x : gt[nod])
if (!comp[x])
dfs2(x, nr);
}
void bfs(int nod, vector<ushort>& drum, vector<pi> g[])
{
int i;
for (i = 1; i <= nr; i++)
drum[i] = inf;
drum[nod] = 0;
queue<pi> q;
q.push({0, nod});
while (!q.empty())
{
auto top = q.front();
q.pop();
int a = top.ss;
for (auto x : g[a])
{
int b = x.ff, w = x.ss;
if (drum[b] > drum[a]+w)
drum[b] = drum[a]+w, q.push({drum[b], b});
}
}
}
void creare_graf_comprimat()
{
for (int i = 1; i <= nr; i++)
{
for (auto x : sc[i])
{
for (auto y : g[x])
{
int cx = comp[x], cy = comp[y];
if (cx == cy)
continue;
if (!ma[{cx, cy}] || ma[{cx, cy}] > 1)
ng[cx].pb({cy, 0}), ma[{cx, cy}] = 1;
}
for (auto y : gt[x])
{
int cx = comp[x], cy = comp[y];
if (cx == cy)
continue;
if (!ma[{cx, cy}])
ng[cx].pb({cy, 1}), ma[{cx, cy}] = 2;
}
}
}
}
int main()
{
fin >> n >> m;
for (i = 1; i <= m; i++)
{
fin >> a >> b;
g[a].pb(b);
gt[b].pb(a);
}
for (i = 1; i <= n; i++)
if (!viz[i])
dfs(i);
reverse(all(f));
nr = 0;
for (auto x : f)
{
if (!comp[x])
{
nr++;
dfs2(x, nr);
}
}
creare_graf_comprimat();
// vector<short> drum[nr+5];
// for (i = 1; i <= nr; i++)
// drum[i].resize(nr+1);
// for (i = 1; i <= nr; i++)
// bfs(i, drum[i], ng);
vector<ushort> drum;
drum.resize(nr+1);
fin >> q;
while (q--)
{
fin >> a >> b;
bfs(comp[a], drum, ng);
fout << drum[comp[b]] << '\n';
}
return 0;
}