Pagini recente » Istoria paginii runda/eusebiu1/clasament | Istoria paginii runda/pascaliada/clasament | Cod sursa (job #1557100) | Istoria paginii runda/lee-clsx/clasament | Cod sursa (job #2009640)
#include<cstdio>
#include<vector>
#include<queue>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;
vector<pair<int,int>>G[MAX_N+1];
queue<int>Q;
int dist[MAX_N+1], ItNode[MAX_N+1], n, m;
bool used[MAX_N+1], cycle;
void Read()
{
int i, x, y, cost;
FILE *fin = fopen("bellmanford.in","r");
fscanf(fin,"%d%d",&n,&m);
for(i=1; i<=m; i++)
{
fscanf(fin,"%d%d%d",&x,&y,&cost);
G[x].push_back(make_pair(y,cost));
}
fclose(fin);
}
void BellmanFord(int source)
{
vector<pair<int,int>>::iterator it;
int i, Node;
for(i=1; i<=n; i++)
dist[i] = oo;
dist[source] = 0;
Q.push(source);
used[source] = true;
cycle = false;
while(!Q.empty() && !cycle)
{
Node = Q.front();
Q.pop();
used[Node] = false;
for(it = G[Node].begin(); it != G[Node].end(); it++)
if(dist[(*it).first] > dist[Node] + (*it).second)
{
dist[(*it).first] = dist[Node] + (*it).second;
if(!used[(*it).first])
{
Q.push((*it).first);
used[(*it).first] = true;
if(++ItNode[(*it).first] > n)
cycle = true;
}
}
}
}
void printDistances()
{
FILE *fout = fopen("bellmanford.out","w");
if(cycle)
fprintf(fout,"Ciclu negativ!\n");
else
{
for(int i=2; i<=n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
}
fclose(fout);
}
int main()
{
Read();
BellmanFord(1);
printDistances();
return 0;
}