Pagini recente » Istoria paginii runda/tsojiround/clasament | Cod sursa (job #3154066) | Cod sursa (job #691956) | Cod sursa (job #2495004) | Cod sursa (job #1878652)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define inf 1522455
#define NMAX 50001
using namespace std;
ifstream f ("bellmanford.in");
ofstream fout ("bellmanford.out");
vector <pair <int, int> > g[NMAX];
int n,m,freq[NMAX],dist[NMAX],viz[NMAX];
void Bellman_Ford()
{
for(int i=1;i<=n;i++)
dist[i]=inf;
queue <int> q;
q.push(1);
viz[1]=1;
dist[1]=0;
while(!q.empty())
{
int top=q.front();
q.pop();
viz[top]=0;
for(int i=0;i<g[top].size();++i)
{
if(dist[g[top][i].first]>dist[top]+g[top][i].second)
{
dist[g[top][i].first]=dist[top]+g[top][i].second;
if(viz[g[top][i].first]) continue;
if(++freq[g[top][i].first]>n)
{
fout<<"Ciclu negativ!";
return;
}
viz[g[top][i].first]=1;
q.push(g[top][i].first);
}
}
}
for(int i=2;i<=n;i++)
fout<<dist[i]<<' ';
}
int main()
{
int i,j,x,y,z;
f>>n>>m;
for(i=1;i<=m;++i)
{
f>>x>>y>>z;
g[x].push_back(make_pair(y,z));
}
Bellman_Ford();
f.close();
fout.close();
return 0;
}