Pagini recente » Cod sursa (job #2940248) | Cod sursa (job #1357485) | Cod sursa (job #3292534) | Cod sursa (job #900167) | Cod sursa (job #3299591)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("obiective.in");
ofstream fout("obiective.out");
typedef long long ll;
const int N = 32e3 + 5;
vector<int> v[N], t[N], s;
set<pair<int, int>> h[N];
unordered_set<int> p;
deque<pair<int, int>> d;
int n, m, a, b, c[N], o, target, j, dist[N];
bool viz[N];
struct query
{
int a, b, poz, rasp;
} q[N];
bool comp1(const query &a, const query &b)
{
return a.b < b.b;
}
bool comp2(const query &a, const query &b)
{
return a.poz < b.poz;
}
void DFS1(int nod)
{
viz[nod] = 1;
for (int e : v[nod])
if (!viz[e])
DFS1(e);
s.push_back(nod);
}
void DFS2(int nod)
{
viz[nod] = 1;
c[nod] = o;
for (int e : t[nod])
if (!viz[e])
DFS2(e);
}
void BFS(int x)
{
d.push_back({x, 0});
for (int i = 1; i <= o; i++)
viz[i] = 0;
for (int i = 1; i <= o; i++)
dist[i] = 1e9;
dist[x] = 0;
viz[x] = 1;
while (!p.empty())
{
int nod = d.front().first;
d.pop_front();
viz[nod] = 1;
if (p.find(nod) != p.end())
{
p.erase(nod);
}
for (pair<int, int> e : h[nod])
{
if (!viz[e.first])
{
int i = e.first;
int noucost = dist[nod] + e.second;
if (noucost < dist[i])
{
dist[i] = noucost;
if (e.second == 0)
d.push_front({i, e.second});
else
d.push_back({i, e.second});
}
}
}
}
d.clear();
}
int main()
{
fin >> n >> m;
while (m--)
{
fin >> a >> b;
v[a].push_back(b);
t[b].push_back(a);
}
for (int i = 1; i <= n; i++)
if (!viz[i])
DFS1(i);
for (int i = 1; i <= n; i++)
viz[i] = 0;
reverse(s.begin(), s.end());
for (int i : s)
if (!viz[i])
{
o++;
DFS2(i);
}
for (int i = 1; i <= n; i++)
for (int e : v[i])
if (c[i] != c[e])
{
h[c[i]].insert({c[e], 0});
h[c[e]].insert({c[i], 1});
}
fin >> m;
for (int i = 1; i <= m; i++)
{
fin >> a >> b;
q[i] = {c[a], c[b], i, 0};
}
sort(q + 1, q + m + 1, comp1);
for (int i = 1; i <= m; i = j)
{
target = q[i].a;
p.clear();
for (j = i; q[j].a == target; j++)
p.insert(q[j].b);
BFS(target);
}
sort(q + 1, q + m + 1, comp2);
for (int i = 1; i <= m; i++)
fout << q[i].rasp << '\n';
fin.close();
fout.close();
return 0;
}