Cod sursa(job #2208341)

Utilizator SchnitzelMannPavaloiu Gabriel SchnitzelMann Data 29 mai 2018 11:27:41
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
#define N 100001
#define M 1000001
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
int nr,vf[2*M],urm[2*M],lst[N];
int viz[N];
queue<int> q;
void bfs(int x)
{
	int p=lst[x],y;
	while(p)
	{
		y=vf[p];//cout<<y<<" ";
		if(!viz[y])
		{
		    q.push(y);
		    viz[y]=viz[x]+1;
		    //cout<<y<<" "<<viz[y]<<" "<<x<<" "<<viz[x]<<"\n";
		}
		p=urm[p];
	}//cout<<x<<"\n";
}
void ad(int x,int y)
{
	vf[++nr]=y;
	urm[nr]=lst[x];
	lst[x]=nr;
}
int main()
{
    int n,m,i,x,y,s;
    in>>n>>m>>s;
	for(i=0;i<m;i++)
	{
		in>>x>>y;
		ad(x,y);
	}
	viz[s]=1;
	q.push(s);
	while(!q.empty())
	{
		bfs(q.front());
		q.pop();
	}
	for(i=1;i<=n;i++)
		out<<viz[i]-1<<" ";
    return 0;
}