Pagini recente » Cod sursa (job #731116) | Cod sursa (job #1190205) | Cod sursa (job #550573) | Cod sursa (job #2253830) | Cod sursa (job #2165305)
#include<cstdio>
#include<vector>
#include<queue>
#include<cctype>
#define MAX_N 100000
#define BUF_SIZE 1 << 19
using namespace std;
vector<int>g[MAX_N + 1];
queue<int>q;
int dist[MAX_N + 1], n, m, S, pos = BUF_SIZE;
char buf[BUF_SIZE];
inline char getChar(FILE *fin) {
if(pos == BUF_SIZE) {
fread(buf,1,BUF_SIZE,fin);
pos = 0;
}
return buf[pos++];
}
inline int read(FILE *fin) {
int res = 0;
char c;
do {
c = getChar(fin);
}while(!isdigit(c));
do {
res = 10*res + c - '0';
c = getChar(fin);
}while(isdigit(c));
return res;
}
void readGraph() {
int x, y;
FILE *fin = fopen("bfs.in","r");
n = read(fin); m = read(fin); S = read(fin);
for(int i = 0; i < m; i++) {
x = read(fin); y = read(fin);
g[x].push_back(y);
}
fclose(fin);
}
void BFS(int node) {
int Node;
for(int i = 1; i <= n; i++)
dist[i] = -1;
dist[node] = 0;
q.push(node);
while(!q.empty()) {
Node = q.front();
q.pop();
for(vector<int>::iterator it = g[Node].begin(); it != g[Node].end(); it++) {
if(dist[*it] == -1) {
dist[*it] = dist[Node] + 1;
q.push(*it);
}
}
}
}
void printDistances() {
FILE *fout = fopen("bfs.out","w");
for(int i = 1; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
fclose(fout);
}
int main() {
readGraph();
BFS(S);
printDistances();
return 0;
}