Pagini recente » Cod sursa (job #1424655) | Cod sursa (job #892288) | Cod sursa (job #840369) | Monitorul de evaluare | Cod sursa (job #515622)
Cod sursa(job #515622)
// http://infoarena.ro/problema/bellmanford
#include <fstream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
#define INFINITY 0x3f3f3f3f
#define cost first
#define location second
int nodes,edges;
vector< list< pair<int,int> > > graph;
vector<int> dist;
vector<bool> inQueue;
priority_queue< pair<int,int>, vector< pair<int,int> >, greater< pair<int,int> > > myHeap;
void read();
bool bellmanFord(int startNode);
void write(bool cycle);
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);
inQueue.resize(nodes+1);
for(int i=1;i<=edges;i++) {
in >> from >> to >> cost;
graph.at(from).push_back(make_pair(cost,to));
}
in.close();
}
bool bellmanFord(int startNode) {
dist.assign(nodes+1,INFINITY);
dist.at(startNode) = 0;
int currentNode;
list< pair<int,int> >::iterator neighbour;
queue<int> myQueue;
for(int i=1;i<=nodes;i++) {
myQueue.push(i);
inQueue.at(i) = true;
}
while(!myQueue.empty()) {
currentNode = myQueue.front();
myQueue.pop();
inQueue.at(currentNode) = false;
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(!inQueue.at(neighbour->location))
myQueue.push(neighbour->location);
}
}
for(int currentNode=1;currentNode<nodes;currentNode++)
for(neighbour=graph.at(currentNode).begin();
neighbour!=graph.at(currentNode).end();
neighbour++)
if(dist.at(neighbour->location) > dist.at(currentNode) + neighbour->cost)
return false;
return true;
}
void write(bool noCycle) {
ofstream out("bellmanford.out");
if(noCycle)
for(int i=2;i<=nodes;i++)
out << dist.at(i) << " ";
else
out << "Ciclu negativ!\n";
out.close();
}