Pagini recente » Cod sursa (job #2518436) | Cod sursa (job #2232784) | Cod sursa (job #1980216) | Cod sursa (job #1819591) | Cod sursa (job #2920694)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX=50001;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
priority_queue < pair <int,int> > h;
vector <pair <int,int> >graph[NMAX];
int visited[NMAX];
int dist[NMAX];
int main()
{
int n,m,x,y,cost;
in>>n>>m;
for(int i=1; i<=m; i++)
{
in>>x>>y>>cost;
graph[x].push_back(make_pair(y,cost));
}
//initializare
for(int i=1; i<=n; i++)
{
dist[i]=INT_MAX;
}
dist[1]=0;
h.push(make_pair(0,1));
visited[1]++;
while(h.empty()==false)
{
x=h.top().second;
h.pop();
for(unsigned int i=0; i<graph[x].size(); i++)
{
y=graph[x][i].first;
cost=graph[x][i].second;
if(dist[y]>dist[x]+cost)
{
dist[y]=dist[x]+cost;
h.push(make_pair(-dist[y],y));
visited[y]++;
}
if(visited[y]==n)
{
out<<"Ciclu negativ!";
return 0;
}
}
}
for(int i=2; i<=n; i++)
{
out<<dist[i]<<" ";
}
return 0;
}