Cod sursa(job #1508226)

Utilizator VisuianMihaiMihai Visuian VisuianMihai Data 22 octombrie 2015 13:50:41
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
//
//  main.cpp
//  BFS
//
//  Created by Mihai Visuian on 22/10/2015.
//  Copyright © 2015 Mihai Visuian. All rights reserved.
//

#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

vector<vector<int> > g;
vector<int> cost;

queue<int>q;

void BFS (int x) {
    cost[x]=0;
    int in = x;
    q.push(x);
    for(;!q.empty();q.pop()) {
        x = q.front();
        for (vector<int>::iterator it = g[x].begin(); it != g[x].end(); it++) {
            if (!cost[*it] && *it != in) {
                q.push(*it);
                cost[*it] = cost[x]+1;
            }
        }
    }
}

int main(int argc, const char * argv[]) {
    
    int n, m, s, x, y;
    
    fin >> n >> m >> s;
    g.resize(n+1);
    cost.assign(n+1,0);
    for (int i = 0; i < m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
    }
    
    BFS(s);
    
    for (int i = 1; i<= n; i++ ) {
        if (!cost[i] && i != s) {
            cost[i] = -1;
        }
        fout << cost[i] << ' ';
    }
    
    fin.close();
    fout.close();
    
    return 0;
}