Pagini recente » Cod sursa (job #341003) | Cod sursa (job #2179613) | Cod sursa (job #3273855) | Cod sursa (job #1998516) | Cod sursa (job #668179)
Cod sursa(job #668179)
// http://infoarena.ro/problema/bfs
#include <fstream>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
#define MAXSIZE 100001
ifstream in("bsf.in");
ofstream out("bsf.out");
int nodes,edges,source;
int dist[MAXSIZE];
queue<int> list;
vector<int> graph[MAXSIZE];
void breadthFirst(int startNode);
int main()
{
in >> nodes >> edges >> source;
int from,to;
for(int i=1;i<=edges;i++)
{
in >> from >> to;
graph[from].push_back(to);
}
in.close();
breadthFirst(source);
for(int i=1;i<=nodes;i++)
if(dist[i] == 0 && i != source)
out << "-1 ";
else
out << dist[i] << " ";
out << "\n";
out.close();
return (0);
}
void breadthFirst(int startNode)
{
int currentNode;
vector<int>::iterator end;
list.push(startNode);
while(!list.empty())
{
currentNode = list.front();
list.pop();
end = graph[currentNode].end();
for(vector<int>::iterator it=graph[currentNode].begin();it!=end;++it)
if(!dist[*it] && source != *it)
{
list.push(*it);
dist[*it] = dist[currentNode] + 1;
}
}
}