Cod sursa(job #2751301)

Utilizator MindralexMindrila Alex Mindralex Data 14 mai 2021 18:48:31
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>

using namespace std;

const int val_max = 44600;

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

bool mat[val_max][val_max];
int v[val_max], cost[val_max], n;

void bfs (int s)
{
    int coada[val_max];
    int l, h;
    l = h = 1;
    coada[l] = s;
    while (l <= h)
    {
        int x = coada[l];
        int cost = v[x];
        cost++;
        for (int i = 1; i <= n; i++)
            if (mat[x][i] && v[i] == -1)
            {
                v[i] = cost;
                coada[++h] = i;
            }
        l++;
    }
}

int main()
{
    int m, s;
    fin >> n >> m >> s;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        mat[x][y] = 1;
    }
    for (int i = 1; i <= n; i++)
        v[i] = -1;
    v[s] = 0;
    bfs(s);
    for (int i = 1; i <= n; i++)
        fout << v[i] << ' ';
    return 0;
}