Cod sursa(job #1337310)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 8 februarie 2015 20:48:52
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

void bfs(vector<int> adjList[], int cost[], int source);

int main()
{
    int N, M, S, x, y, i;
    ifstream f("bfs.in");
    f >> N >> M >> S;
    vector<int> adjList[N + 1];
    int cost[N + 1];
    for (i = 1; i <= N; i++)
        cost[i] = -1;

    for (i = 1; i <= M; i++)
    {
        f >> x >> y;
        adjList[x].push_back(y);
    }
    f.close();

    bfs(adjList, cost, S);

    ofstream g("bfs.out");
    for (i = 1; i <= N; i++)
        g << cost[i] << " ";
    g.close();

    return 0;
}

void bfs(vector<int> adjList[], int cost[], int source)
{
    queue<int> q;
    q.push(source);
    cost[source] = 0;

    int x;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        for (auto i = adjList[x].begin(); i != adjList[x].end(); i++)
            if (cost[*i] == -1)
            {
                q.push(*i);
                cost[*i] = cost[x] + 1;
            }
    }
}