Cod sursa(job #1974137)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 26 aprilie 2017 22:09:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
struct graph{vector <int> v;};
queue <int> q;
graph G[100001];
int cost[100001];
inline void BFS(const int &x)
{
    int i,nod;
    q.push(x);
    cost[x]=0;
    while(!q.empty())
    {
        nod=q.front();
        q.pop();
        for(i=0;i<G[nod].v.size();i++)
            if(cost[nod]+1<cost[G[nod].v[i]])
            {
                cost[G[nod].v[i]]=cost[nod]+1;
                q.push(G[nod].v[i]);
            }
    }
}
int main()
{int n,m,start,k,i,j;
f>>n>>m>>start;
for(k=0;k<m;k++)
{
    f>>i>>j;
    G[i].v.push_back(j);
}
fill(cost+1,cost+n+1,INF);
BFS(start);
replace(cost+1,cost+n+1,INF,-1);
for(i=1;i<=n;i++)
g<<cost[i]<<' ';

    return 0;
}