Pagini recente » Cod sursa (job #1664746) | Cod sursa (job #2282136) | Clasament cvuri | Cod sursa (job #2964839) | Cod sursa (job #492280)
Cod sursa(job #492280)
#include<fstream>
#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<queue>
#include<bitset>
#include<cstring>
#define MAXN 50001
#define INF 0x17D7841
using namespace std;
typedef unsigned short uint16;
typedef pair<pair<uint16,uint16>,short> Edge;
struct Compare
{
const bool operator() (const Edge& a, const Edge& b) const
{
return a.second<b.second;
}
};
bool BellmanFord(const vector<vector<Edge> >& edges,
const int n,
const int m,
const uint16 s,
int *dist)
{
queue<uint16> Q;
uint16 count[MAXN]={0};
bool neg_cycle=false;
bitset<MAXN> inQ;
memset(dist,0x3f,n*sizeof(int));
dist[s]=0;
Q.push(s);
inQ[s]=true;
while(!Q.empty() && !neg_cycle)
{
const int node=Q.front();
Q.pop();
inQ[node]=false;
for(int j=0; j<(int)edges[node].size(); ++j)
if(dist[edges[node][j].first.first]<INF)
{
if(dist[edges[node][j].first.first] + edges[node][j].second < dist[edges[node][j].first.second])
{
dist[edges[node][j].first.second]=dist[edges[node][j].first.first] + edges[node][j].second;
if(!inQ[edges[node][j].first.second])
{
if(count[edges[node][j].first.second]>n)
{
neg_cycle=true;
}
else
{
Q.push(edges[node][j].first.second);
inQ[edges[node][j].first.second]=true;
count[edges[node][j].first.second]++;
}
}
}
}
}
return neg_cycle;
}
int main()
{
uint16 a,b;
short c;
int n,m,dist[MAXN];
fstream fin("bellmanford.in", fstream::in);
fstream fout("bellmanford.out", fstream::out);
vector<vector<Edge> > edges;
fin>>n>>m;
edges.resize(n);
for(int i=0; i<m; ++i)
{
fin>>a>>b>>c;
edges[a-1].push_back(make_pair(make_pair(a-1,b-1),c));
}
if(BellmanFord(edges,n,m,0,dist))
{
fout<<"Ciclu negativ!\n";
}
else
{
for(int i=1; i<n; ++i)
{
fout<<dist[i]<<" ";
}
}
fin.close();
fout.close();
return 0;
}