Cod sursa(job #447572)

Utilizator digistyl3Janos Levai digistyl3 Data 29 aprilie 2010 02:57:47
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
/* 
 * File:   main.cpp
 * Author: Johnny
 *
 * Created on April 29, 2010, 1:53 AM
 */

#include <stdlib.h>
#include <fstream>
#include <list>
#include <queue>

using namespace std;

/*
 * 
 */
int n, m, s;

int main(int argc, char** argv) {
    fstream fin("bfs.in", ios_base::in);
    fin >> n >> m >> s;
    --s;
    list<int> rel[n];
    int x, y;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y;
        rel[x - 1].push_back(y - 1);
    }
    fin.close();

    bool was[n];
    int dist[n];
    for (int i = 0; i < n; ++i) {
        was[i] = false;
        dist[i] = -1;
    }
    fstream fout("bfs.out", ios_base::out);
    queue<int> q;
    q.push(s);
    q.push(-1); // Signalling a new depth
    was[s] = true;
    dist[s] = 0;
    int d = 1;
    while (q.size() > 1) {
        x = q.front();
        q.pop();
        if (x == -1) {
            ++d;
            q.push(-1);
        }
        else
            for (list<int>::const_iterator it = rel[x].begin(); it != rel[x].end(); ++it)
                if (!was[*it]) {
                    q.push(*it);
                    was[*it] = true;
                    dist[*it] = d;
                }
    }
    for (int i = 0; i < n; ++i)
        fout << dist[i] << ' ';
    fout.close();

    return (EXIT_SUCCESS);
}