Pagini recente » Cod sursa (job #1028022) | Cod sursa (job #868080) | Cod sursa (job #2628348) | Cod sursa (job #1677430) | Cod sursa (job #803520)
Cod sursa(job #803520)
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 50001
#define INF 999999999
using namespace std;
FILE *inFile = fopen ("bellmanford.in", "r");
FILE *outFile = fopen ("bellmanford.out", "w");
struct nod
{
int v;
int cost;
};
int n;
int nr[NMAX];
int cost[NMAX];
struct comp
{
bool operator () (const int &a, const int &b) const
{
return cost[a] > cost[b];
}
};
vector <nod> G[NMAX];
priority_queue <int, vector <int>, comp> Q;
void read()
{
int m;
int x;
nod y;
fscanf (inFile, "%d %d\n", &n, &m);
while (m --)
{
fscanf (inFile, "%d %d %d\n", &x, &y.v, &y.cost);
G[x].push_back(y);
}
}
bool bellmanford()
{
for (int i = 2; i <= n; cost[i] = INF, ++ i);
Q.push(1);
while (!Q.empty())
{
int v = Q.top();
Q.pop();
for (unsigned int i = 0; i < G[v].size(); ++ i)
{
nod aux = G[v][i];
if (cost[v] + aux.cost < cost[aux.v])
{
cost[aux.v] = cost[v] + aux.cost;
Q.push(aux.v);
++ nr[v];
}
}
if (nr[v] > n)
return 0;
}
return 1;
}
void write()
{
for (int i = 2; i <= n; ++ i)
if (cost[i] == INF)
fprintf (outFile, "0 ");
else
fprintf (outFile, "%d ", cost[i]);
fprintf (outFile, "\n");
}
int main()
{
read();
if (!bellmanford())
fprintf (outFile, "Ciclu negativ!");
else
write();
return 0;
}