Pagini recente » Cod sursa (job #857203) | Cod sursa (job #1938241) | Cod sursa (job #2692332) | Cod sursa (job #665300) | Cod sursa (job #629757)
Cod sursa(job #629757)
#include<cstdio>
#include<queue>
using namespace std;
FILE *f,*g;
struct list {
int neigh;
list *next;
};
list *listad[100001];
int viz[100001];
int N,S,M;
void ReadData() {
fscanf(f,"%d %d %d", &N, &M,&S);
int x, y;
for (int i = 0; i < M; i++) {
fscanf(f,"%d %d ", &x, &y);
list *aux = new list;
aux->neigh = y;
aux->next = listad[x];
listad[x] = aux;
}
}
void BFS(int source){
queue<pair<int, int> > neigh;
viz[source] = 1;
neigh.push(make_pair(source, 0));
pair<int, int> current;
list *aux;
while (!neigh.empty()){
current = neigh.front();
neigh.pop();
aux = listad[current.first];
while (aux) {
if (!viz[aux->neigh]) {
viz[aux->neigh] = current.second+1;
neigh.push(make_pair(aux->neigh, current.second + 1));
}
aux = aux->next;
}
}
}
void WriteData()
{
viz[S]=-1;
for(int i=1;i<=N;i++)
{
if(viz[i]==0)
fprintf(g,"-1 ");
else
if(viz[i]==-1)
fprintf(g,"0 ");
else
fprintf(g,"%d ",viz[i]);
}
fprintf(g,"\n ");
}
int main() {
f = fopen("bfs.in", "r");
g = fopen("bfs.out", "w");
ReadData();
BFS(S);
WriteData();
fclose(f);
fclose(g);
return 0;
}