Cod sursa(job #1588445)

Utilizator AnesthesicChereches Sergiu Alexandru Anesthesic Data 3 februarie 2016 08:36:28
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 100005
using namespace std;


void get_data (int &n, int &m, vector <int> v[nmax], int dist[nmax], int &s){
    ifstream fin ("bfs.in");
    fin >> n >> m >> s;
    for (int i = 1; i <= n; i++)
        dist[i] = -1;
    for (int i = 1; i <= m; i++){
        int x, y;
        fin >> x >> y;
        v[x].push_back (y);
    }
}

void bfs (int n, int s, vector <int> v[nmax], int dist[nmax]){
    dist[s] = 0;
    queue <int> q;
    q.push (s);
    while (!q.empty ()){
        int current = q.front ();
        for (auto vecin : v[current])
            if (dist[vecin] == -1){
                dist[vecin] = dist[current] + 1;
                q.push (vecin);
            }
        q.pop ();
    }
}

void print_data (int n, int dist[nmax]){
    ofstream fout ("bfs.out");
    for (int i = 1; i <= n; i++)
        fout << dist[i] << " ";
}

int main(){
    int n, m, s;;
    int dist[nmax];
    vector <int> v[nmax];
    get_data (n, m, v, dist, s);
    bfs (n, s, v, dist);
    print_data (n, dist);

    return 0;
}