Cod sursa(job #1108343)

Utilizator A63N7pTudor Nazarie A63N7p Data 15 februarie 2014 16:41:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 100005;
int N, M, S;
vector<int> edges[NMAX];
queue< pair<int, int> > nodes;
int dist[NMAX];

inline void read() {
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    scanf("%i%i%i", &N, &M, &S);
    int from, to;
    for (int i = 0; i < M; i++) {
        scanf("%i %i", &from, &to);
        edges[from].push_back(to);
    }
}

inline void solve() {
    nodes.push(make_pair(S, 0));
    while (!nodes.empty()) {
        pair<int, int> node = nodes.front();
        nodes.pop();
        for (int i = 0; i < (int)edges[node.first].size(); i++) {
            int index = edges[node.first][i];
            if (!dist[index] && index != S) {
                dist[index] = 1 + node.second;
                nodes.push(make_pair(index, dist[index]));
            }
        }
    }
}

void printSolution() {
    for (int i = 1; i <= N; i++)
        if(dist[i])
            printf("%i ", dist[i]);
        else if( i == S )
            printf("0 ");
        else
            printf("-1 ");
}

int main() {
    read();
    solve();
    printSolution();
    return 0;
}