Pagini recente » Cod sursa (job #1900746) | Cod sursa (job #1838265) | Cod sursa (job #2208972) | Cod sursa (job #1702246) | Cod sursa (job #2073724)
#include<fstream>
#include<list>
#include<queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
list<int>l[100005];
queue<int>c;
bool viz[100005];
int dist[100005], cost[100005];
int n, m, nr_comp, s;
void citire()
{
f >> n >> m >> s;
int x, y;
while(f >> x >> y)
l[x].push_back(y);
}
int bfs(int sf){
if(sf == s) return 0;
c.push(s);
viz[s] = 1;
cost[s] = 0;
while(!c.empty()){
int nc = c.front();
list<int>::iterator it;
for(it = l[nc].begin(); it != l[nc].end(); it++){
if(!viz[*it]){
cost[*it] = cost[nc] + 1;
c.push(*it);
viz[*it] = true;
}
if(*it == sf){
while(!c.empty())
c.pop();
return cost[sf];
}
}
c.pop();
}
return -1;
}
void solve(){
dist[s] = 0;
for(int i = 1; i <= n; i++){
for(int k = 1; k <= n; k++)
viz[k] = 0;
dist[i] = bfs(i);
}
for(int i = 1; i <= n; i++)
g << dist[i] << ' ';
}
int main(){
citire();
solve();
return 0;
}