Pagini recente » Cod sursa (job #741966) | Cod sursa (job #2858400) | Cod sursa (job #973515) | Cod sursa (job #61255) | Cod sursa (job #442763)
Cod sursa(job #442763)
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
using namespace std;
typedef unsigned long ulong;
#define NDEBUG
#ifdef NDEBUG
#define dbg 0 && (*((ostream *) 0))
#else
#define dbg clog
#endif
class BFS
{
public:
BFS(std::vector<std::vector<ulong>* >& adjacencyList, ulong nVertices, ulong sourceNode)
: numVertices(nVertices), source(sourceNode), adjList(adjacencyList)
{
isVisited.resize(nVertices + 1, false);
costs.resize(nVertices + 1, 0);
}
public:
void execute()
{
bfs(source);
for(ulong i = 1; i <= numVertices; i++)
{
if(!isVisited[i])
costs[i] = -1;
}
}
void bfs(ulong node)
{
std::list<ulong> queue;
queue.push_back(node);
while(!queue.empty())
{
ulong current = queue.back();
isVisited[current] = true;
queue.pop_back();
std::vector<ulong> * neighbours = adjList[current];
if(!neighbours)
continue;
for(ulong i = 0; i < neighbours->size(); i++)
{
ulong vertex = (*neighbours)[i];
if(!isVisited[vertex])
{
queue.push_back(vertex);
costs[vertex] = costs[current] + 1;
}
}
}
}
const std::vector<long>& getCosts() const { return costs; }
private:
ulong numVertices;
ulong source;
std::vector<std::vector<ulong>* >& adjList;
std::vector<long> costs;
std::vector<bool> isVisited;
};
int main(int argc, char * argv[])
{
const char * inFile = "bfs.in";
const char * outFile = "bfs.out";
ifstream fin(inFile);
#ifndef NDEBUG
if(!fin || !fout)
{
cerr << "Error opening one of \"" << inFile << "\" or \"" << outFile << "\"" << endl;
return -1;
}
#endif
/**
* Read the data in.
*/
ulong n, m, source;
fin >> n >> m >> source;
std::vector<std::vector<ulong>* > adjList;
adjList.resize(n + 1, NULL);
ulong x, y;
for(ulong i = 0; i < m; i++)
{
fin >> x;
fin >> y;
if(adjList[x] == NULL)
{
adjList[x] = new std::vector<ulong>();
}
adjList[x]->push_back(y);
}
/**
* Solve the problem.
*/
BFS bfs(adjList, n, source);
bfs.execute();
const std::vector<long>& costs = bfs.getCosts();
ofstream fout(outFile);
for(std::vector<long>::const_iterator it = costs.begin() + 1;
it != costs.end(); ++it)
{
fout << *it << " ";
}
/**
* Cleanup!
*/
for(ulong i = 0; i < adjList.size(); i++)
{
if(adjList[i] != NULL)
delete adjList[i];
}
fout.close();
fin.close();
return 0;
}