Cod sursa(job #1357317)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 23 februarie 2015 21:18:49
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <algorithm>
#include <queue>
#include <cstring>
#define pb push_back
#define mp make_pair
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

typedef long long ll;
typedef unsigned long long ull;
typedef pair < int, int> pi;
typedef vector< int > vi;
typedef vector< pair< int, int > > vpi;

int N, M, S, x, y, D[100005];
vector < int > G[100005];
queue < int > Q;

void bfs(int sursa)
{
    for (int i=1; i<=N; ++i)
        D[i]=(1<<30);
    D[sursa]=0; Q.push(sursa);

    while (Q.size())
    {
        int nod=Q.front(); Q.pop();
        vector <int>::iterator it=G[nod].begin();
        for (; it!=G[nod].end(); ++it)
            if (D[*it]>D[nod]+1)
                D[*it]=D[nod]+1, Q.push(*it);
    }
}

int main()
{
    f>>N>>M>>S;
    for (int i=1; i<=M; ++i)
        f>>x>>y, G[x].pb(y);
    bfs(S);
    for (int i=1; i<=N; ++i)
        if (D[i]<(1<<30)) g<<D[i]<<' ';
            else g<<-1<<' ';
	return 0;
}