Cod sursa(job #1247030)

Utilizator bogdan10bosBogdan Sitaru bogdan10bos Data 21 octombrie 2014 23:22:52
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

struct nod
{
    int x, y;
}nd, newNd;

int n, m, x, y, i, z, a[100005];

vector <int> v[100005];
vector <int>::iterator it;
queue <nod> q;

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    scanf("%d%d%d", &n, &m, &z);
    while(m--)
    {
        scanf("%d%d", &x, &y);
        v[x].push_back(y);
    }
    //for(i=1;i<=n;i++)
    //    a[i]=1<<30;
    nd.y=z;nd.x=1;
    q.push(nd);
    while(!q.empty())
    {
        nd=q.front();
        if(nd.x<a[nd.y]||a[nd.y]==0) a[nd.y]=nd.x;
        for(it=v[nd.y].begin();it!=v[nd.y].end();it++)
        {
            x=*it;
            if(a[x]==0||a[x]>nd.x+1)
            {
                newNd.y=x;
                newNd.x=nd.x+1;
                q.push(newNd);
            }
        }
        q.pop();
    }
    for(i=1;i<=n;i++)
        if(a[i]==1<<30) printf("-1 ");
        else printf("%d ", a[i]-1);
    return 0;
}