Cod sursa(job #1166091)

Utilizator dariusdariusMarian Darius dariusdarius Data 3 aprilie 2014 11:09:49
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int MAX_N = 100005;

vector<int> graph[MAX_N];
int cost[MAX_N];

int main() {
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    int n, m, source;
    fin >> n >> m >> source;
    for(int i = 1; i <= m; ++ i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }
    
    queue<int> q;
    for(int i = 1; i <= n; ++ i) {
        cost[i] = -1;
    }
    cost[source] = 0;
    q.push(source);
    while(q.empty() == false) {
        //q.front()
        int node = q.front();
        for(int j = 0; j < graph[node].size(); ++ j) {
            if(cost[graph[node][j]] == -1) {
                cost[graph[node][j]] = cost[node] + 1;
                q.push(graph[node][j]);
            }
        }
        q.pop();
    }

    for(int i = 1; i <= n; ++ i) {
        fout << cost[i] << " ";
    }
    fout << "\n";
    
    return 0;
}