Pagini recente » Cod sursa (job #2306718) | Cod sursa (job #2253782) | Cod sursa (job #1706022) | Cod sursa (job #908610) | Cod sursa (job #931996)
Cod sursa(job #931996)
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 50005
#define INF 2000000000
using namespace std;
int n, nr[NMAX], cost[NMAX];
struct comp
{
/// gen dijkstra
bool operator () (const int &a, const int &b) const
{
return cost[a] > cost[b];
}
};
struct nod
{
int v;
int cost;
};
vector <nod> g[NMAX];
priority_queue <int, vector <int>, comp> q;
void citire()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int m, x;
nod y;
scanf ("%d %d", &n, &m);
for(int i = 0; i < m; i++)
{
scanf ("%d %d %d", &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 (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 afisare()
{
if (!bellmanford())
printf ("Ciclu negativ!\n");
else
{
for (int i = 2; i <= n; i++)
if (cost[i] == INF)
printf("0 ");
else
printf("%d ", cost[i]);
printf("\n");
}
}
int main()
{
citire();
afisare();
return 0;
}