Pagini recente » Cod sursa (job #2958431) | Cod sursa (job #2848269) | Cod sursa (job #2185543) | Cod sursa (job #534326) | Cod sursa (job #515922)
Cod sursa(job #515922)
// http://infoarena.ro/problema/bellmanford
#include <fstream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
#define INFINITY 0x3f3f3f3f
#define location first
#define cost second
int nodes,edges;
vector< list< pair<int,int> > > graph;
vector<int> dist;
vector<bool> visit;
vector<int> timesVisited;
queue<int> myQueue;
void read();
bool bellmanFord(int startNode);
void write(bool status);
int main() {
read();
write(bellmanFord(1));
return (0);
}
void read() {
ifstream in("bellmanford.in");
int from,to,cost;
in >> nodes >> edges;
graph.resize(nodes+1);
dist.resize(nodes+1);
visit.resize(nodes+1);
timesVisited.resize(nodes+1);
for(int i=1;i<=edges;i++) {
in >> from >> to >> cost;
graph.at(from).push_back(make_pair(to,cost));
}
in.close();
}
bool bellmanFord(int startNode) {
dist.assign(nodes+1,INFINITY);
dist.at(startNode) = 0;
int currentNode;
list< pair<int,int> >::iterator neighbour;
myQueue.push(startNode);
while(!myQueue.empty()) {
currentNode = myQueue.front();
for(neighbour=graph.at(currentNode).begin();
neighbour!=graph.at(currentNode).end();
neighbour++)
if(dist.at(neighbour->location) > dist.at(currentNode) + neighbour->cost) {
dist.at(neighbour->location) = dist.at(currentNode) + neighbour->cost;
if(!visit.at(neighbour->location)) {
timesVisited.at(neighbour->location)++;
if(timesVisited.at(neighbour->location) > nodes)
return false;
}
myQueue.push(neighbour->location);
visit.at(neighbour->location) = true;
}
visit.at(currentNode) = false;
myQueue.pop();
}
return true;
}
void write(bool status) {
ofstream out("bellmanford.out");
if(status)
for(int i=2;i<=nodes;i++)
out << dist.at(i) << " ";
else
out << "Ciclu negativ!\n";
out.close();
}