Cod sursa(job #3271307)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 25 ianuarie 2025 17:56:25
Problema Obiective Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <fstream>
#include <bits/stdc++.h>

using namespace std;
ifstream fin("obiective.in");
ofstream fout("obiective.out");
int n, m, i, j, gri[32005], nr, comp[32005], x, y, dist[32005], t;
vector <int> v[32005], vt[32005], component[32005], g[32005];
stack <int> st;
queue <int> q;
bool viz[32005];
void dfs(int nod)
{
    viz[nod]=1;
    for(auto i: v[nod])
        if(viz[i]==0)
            dfs(i);
    st.push(nod);
}
void dfs1(int nod)
{
    viz[nod]=1;
    component[nr].push_back(nod);
    comp[nod]=nr;
    for(auto i: vt[nod])
        if(viz[i]==0)
            dfs1(i);
}
int main()
{
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
    dfs(1);
    for(i=1; i<=n; i++)
        viz[i]=0;
    while(!st.empty())
    {
        int x=st.top();
        st.pop();
        if(viz[x]==0)
        {
            nr++;
            dfs1(x);
        }
    }
    for(i=1; i<=n; i++)
        for(auto j: v[i])
            if(comp[i]!=comp[j])
            {
                gri[comp[j]]++;
                g[comp[i]].push_back(comp[j]);
            }
    for(i=1; i<=nr; i++)
        if(gri[i]==0)
            q.push(i);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto i: g[x])
        {
            gri[i]--;
            dist[i]=dist[x]+1;
            if(gri[i]==0)
                q.push(i);
        }
    }
    fin>>t;
    while(t--)
    {
        fin>>x>>y;
        x=comp[x];
        y=comp[y];
        if(dist[x]-dist[y]<0)
            fout<<0<<'\n';
        else
            fout<<dist[x]-dist[y]<<'\n';
    }
    return 0;
}