Pagini recente » Cod sursa (job #416212) | Cod sursa (job #2905700) | Cod sursa (job #1310453) | Cod sursa (job #1655722) | Cod sursa (job #456221)
Cod sursa(job #456221)
/*
* =====================================================================================
*
* Filename: dijkstra.cpp
*
* Description:
*
* Author: Victor Carbune ([email protected])
* Info: Grupa 325, Seria CA
*
* =====================================================================================
*/
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#define INF 1000000
#define MAXN 50010
using namespace std;
typedef struct _edge
{
int x, y, cost;
} edge;
vector< pair<int, int> > *graf;
int n, m, *d;
ifstream in("bellmanford.in", ifstream::in);
ofstream out("bellmanford.out", ofstream::out);
void read_data()
{
int x, y, cost;
in >> n >> m;
graf = new vector< pair<int, int> >[n];
for (int i = 0; i < m; i++) {
in >> x >> y >> cost;
x--, y--;
graf[x].push_back(make_pair(y, cost));
}
}
int bellmanford(int s)
{
d = new int[n];
for (int i = 0; i < n; i++)
d[i] = INF;
d[s] = 0;
vector<int> in_queue(MAXN, 0), count(MAXN, 0);
queue<int> Q;
Q.push(s);
in_queue[s] = 1;
int nod;
while (!Q.empty()) {
nod = Q.front();
Q.pop();
in_queue[nod] = 0;
for (int i = 0; i < graf[nod].size(); i++) if (d[nod] < INF) {
if (d[graf[nod][i].first] > d[nod] + graf[nod][i].second) {
d[graf[nod][i].first] = d[nod] + graf[nod][i].second;
if (!in_queue[graf[nod][i].first]) {
if (count[graf[nod][i].first] > n) {
return 1;
}
Q.push(graf[nod][i].first);
in_queue[graf[nod][i].first] = 1;
count[graf[nod][i].first]++;
}
}
}
}
return 0;
}
int main() {
read_data();
if (bellmanford(0)) {
printf("Ciclu negativ!\n");
} else {
for (int i = 1; i < n; i++)
out << (d[i] == INF ? 0:d[i]) << " ";
out << endl;
}
return 0;
}