Pagini recente » Cod sursa (job #1821570) | Cod sursa (job #2230813) | Cod sursa (job #1729438) | Cod sursa (job #1048148) | Cod sursa (job #2232121)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
struct point
{
int nod;
int cost;
};
bool operator<(point a, point b)
{
return a.cost > b.cost;
}
#define INF 0x3f3f3f3f
#define Gmax 50010
vector <pair <int, int> > G[Gmax];
priority_queue <point> pq;
int dist[Gmax];
int N,M;
int main()
{
f>>N>>M;
for(int i=1; i<=M; i++)
{
int x,y,c;
f>>x>>y>>c;
G[x].push_back(make_pair(y,c));
}
pq.push({1,0});
memset(dist, 0x3f, sizeof(dist));
while(!pq.empty())
{
int nod = pq.top().nod;
int cost = pq.top().cost;
pq.pop();
if(dist[nod] != INF)
continue;
dist[nod] = cost;
for(int i=0; i<G[nod].size(); i++)
{
pq.push({G[nod][i].first,cost + G[nod][i].second});
}
}
for(int i=2; i<=N; i++)
{
if(dist[i]==INF) g<<0<<' ';
else
g<<dist[i] <<' ';
}
//g<<"Ciclu negativ!";
return 0;
}