Pagini recente » Cod sursa (job #287379) | Cod sursa (job #947164) | Cod sursa (job #916697) | Cod sursa (job #449497) | Cod sursa (job #2520489)
#include <bits/stdc++.h>
#define oo 1e9+1
#define Dim 50001
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int N,M,x,y,z,D[Dim],R[Dim];
bool there[Dim];
typedef pair < int,int > pi;
vector < pi > V[Dim];
struct cmp
{
bool operator () ( int x,int y)
{
if( D[x] < D[y] ) return 1;
else
if(D[x]==D[y])
{
if( x<y ) return 1;
else return 0;
}
else return 0;
}
};
set < int,cmp > S;
int main()
{
f>>N>>M;
for(int i=1;i<=M;i++)
{
f>>x>>y>>z;
V[x].push_back({y,z});
}
for(int i=2;i<=N;i++) D[i]=oo;
D[1]=0;
there[1]=1;
S.insert(1);
int cnt=0;
while(!S.empty())
{
int nod=*S.begin();
S.erase(S.begin());
there[nod]=0;
R[nod]++;
if( R[nod] == N )
{
g<<"Ciclu negativ!";
return 0;
}
for(unsigned int i=0;i<V[nod].size();i++)
{
int vecin=V[nod][i].first;
int cost=V[nod][i].second;
if( D[vecin] > D[nod] + cost )
{
if( there[vecin]==1 ) S.erase( S.find(vecin) );
D[vecin]=D[nod]+cost;
S.insert(vecin);
there[vecin]=1;
}
}
}
for(int i=2;i<=N;i++) g<<D[i]<<" ";
return 0;
}