Cod sursa(job #2275735)

Utilizator razviii237Uzum Razvan razviii237 Data 3 noiembrie 2018 14:55:06
Problema BFS - Parcurgere in latime Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const int maxn = 105;

ifstream f("bfs.in");
ofstream g("bfs.out");

int n, m, p, x, y, i;
vector <int> lst[maxn];
queue <int> q;
int is[maxn];

inline void add(int x, int y)
{
    lst[x].push_back(y);
}

void bfs(int p)
{
    is[p] = 1;
    q.push(p);

    while(!q.empty())
    {
        int x = q.front();
        for(auto u : lst[x]) {
            if(is[u] == 0) {
                is[u] = is[x] + 1;
                q.push(u);
            }
        }
        q.pop();
    }
}

int main()
{
    f >> n >> m >> p;

    for(i = 1; i <= m; i ++)
    {
        f >> x >> y;
        add(x, y);
        //add(y, x);
    }

    for(i = 1; i <= n; i ++) {
        sort(lst[i].begin(), lst[i].end());
    }

    bfs(p);

    for(i = 1; i <= n; i ++) {
    if(is[i] == 0)
        g << "-1 ";
    else
        g << is[i] - 1 << ' ';
    }

    f.close();
    g.close();
    return 0;
}