Pagini recente » Cod sursa (job #1772572) | Cod sursa (job #2454190) | Cod sursa (job #1877201) | Cod sursa (job #2692398) | Cod sursa (job #1166851)
#include<cstdio>
#include<vector>
#include<queue>
#define M 2000000000
#define maxN 50001
using namespace std;
FILE *f=fopen("bellmanford.in","r");
FILE *g=fopen("bellmanford.out","w");
struct nod
{
int inf,c;
};
vector<nod>L[maxN];
queue<int>q;
bool viz[maxN];
int cost[maxN],nr[maxN],n,m;
void bellman()
{
int i,nodcur,j;
for(i=1;i<=n;i++)cost[i]=M;
cost[1]=0;
q.push(1);nr[1]++;
while(!q.empty())
{
nodcur=q.front();
q.pop();viz[nodcur]=false;
for(j=0;j<L[nodcur].size();j++)
if(cost[L[nodcur][j].inf]>cost[nodcur]+L[nodcur][j].c)
{
cost[L[nodcur][j].inf]=cost[nodcur]+L[nodcur][j].c;
if(viz[L[nodcur][j].inf]==false)
{
viz[L[nodcur][j].inf]=true;
q.push(L[nodcur][j].inf);
nr[L[nodcur][j].inf]++;
if(nr[L[nodcur][j].inf]>n)
{
fprintf(g,"Ciclu negativ!");
return;
}
}
}
}
}
void afisare()
{
int i;
for(i=2;i<=n;i++)
fprintf(g,"%d ",cost[i]);
}
int main()
{
int i,x,y,z;
nod aux;
fscanf(f,"%d%d",&n,&m);
for(i=1;i<=m;i++)
{
fscanf(f,"%d%d%d",&x,&y,&z);
aux.inf=y;
aux.c=z;
L[x].push_back(aux);
}
bellman();
afisare();
return 0;
}