Cod sursa(job #67724)

Utilizator victorsbVictor Rusu victorsb Data 25 iunie 2007 13:42:14
Problema Obiective Scor 5
Compilator cpp Status done
Runda preONI 2007, Runda Finala, Clasele 11-12 Marime 2.01 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

#define Nmax 32005
#define Cmax 1505
#define pb push_back
#define vec lv[nod][i]

int n, m, ct;
vector<int> lv[Nmax];
vector<int> lv1[Nmax];
vector<int> lv2[Nmax];
int list[Nmax], v[Nmax];
int mat[Cmax][Cmax];

void citire()
{
    int i, a, b;
    
    scanf("%d %d\n", &n, &m);
    for (i = 1; i <= m; ++i)
    {
        scanf("%d %d\n", &a, &b);
        lv[a].pb(b);
    }
}

void df1(int nod)
{
    int i, lim = lv[nod].size();
    
    v[nod] = 1;
    
    for (i = 0; i < lim; ++i)
        if (!v[vec])
            df1(vec);
    
    list[++ct] = nod;
}

void df2(int nod)
{
    int i, lim = lv[nod].size();
    
    v[nod] = ct;
    
    for (i = 0; i < lim; ++i)
        if (!v[vec])
            df2(vec);
}

void solve()
{
    int i, j, k, v1, v2, t;
    
    for (i = 1; i <= n; ++i)
        if (!v[i])
            df1(i);
    
    memset(v, 0, sizeof(v));
    ct = 0;
    for (i = 1; i <= n; ++i)
        if (!v[list[i]])
        {
            ++ct;
            df2(list[i]);
        }

    memset(mat, 0x3f, sizeof(mat));
    for (i = 1; i <= ct; ++i) mat[i][i] = 0;
    
    for (i = 1; i <= n; ++i)
        for (j = 0; j < lv[i].size(); ++j)
            if (v[i] != v[lv[i][j]])
            {
               v1 = v[i];
               v2 = v[lv[i][j]];
               mat[v1][v2] = 0;
               mat[v2][v1] = min(mat[v2][v1], 1);
            }

    n = ct;
    
    for (k = 1; k <= n; ++k)
        for (i = 1; i <= n; ++i)
            for (j = 1; j <= n; ++j)
                if (mat[i][k] + mat[k][j] < mat[i][j]) mat[i][j] = mat[i][k] + mat[k][j];

    scanf("%d\n", &t);
    for (i = 1; i <= t; ++i)
    {
        scanf("%d %d\n", &v1, &v2);
        printf("%d\n", mat[v[v1]][v[v2]]);
    }
}

int main()
{
    freopen("obiective.in", "r", stdin);
    freopen("obiective.out", "w", stdout);
    citire();
    solve();
    return 0;
}