Cod sursa(job #923441)

Utilizator StefansebiStefan Sebastian Stefansebi Data 23 martie 2013 16:42:15
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include<queue>
#include<fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int a[10000][10000], marc[10000], cost[10000], s, n, m;
queue <int> q;

int bfs(int start) {
    int i, x;
    cost[start] = 0;
    marc[start] = 1;
    q.push(start);
    while (!q.empty()) {
        x = q.front();
        q.pop();
        for (i = 1; i <= n; i++) {
            if (a[x][i] == 1 and not marc[i]) {
                q.push(i); marc[i] = 1; cost[i] = cost[x] + 1;
            }
        }
    }
}

void setcost() {
    int i;
    for (i = 1; i <= n; i++)
        cost[i] = -1;
}

void afiscost() {
    int i;
    for (i = 1; i <= n; i++)
        fout << cost[i] << " ";
}

int main() {
    int i, x, y;
    fin >> n >> m >> s;
    for (i = 1; i <= m; i++) {
        fin >> x >> y;
        a[x][y] = 1;
    }
    setcost();
    bfs(s);
    afiscost();
}