Pagini recente » Cod sursa (job #1926261) | Borderou de evaluare (job #920512) | Cod sursa (job #729514) | Cod sursa (job #993213) | Cod sursa (job #1610132)
#include <cstdio>
#include <climits>
#include <vector>
#include <queue>
#define inf INT_MAX
#define po 50001
using namespace std;
int n,m,dist[po];
vector<pair<int,int> > nods[po];
queue<int> coada;
bool viz[po];
FILE *f1;
int main()
{
f1=fopen("bellmanford.in","r");
fscanf(f1,"%d%d",&n,&m);
for(int i=1; i<=m; i++)
{
int a,b,c;
fscanf(f1,"%d%d%d",&a,&b,&c);
nods[a].push_back(make_pair(b,c));
}
for(int i=1; i<=n; i++)
{
dist[i]=inf;
}
dist[1]=0;
coada.push(1);
viz[1]=true;
while(!coada.empty())
{
int a=coada.front();coada.pop();
vector<pair<int,int> > ::iterator it;
for(it=nods[a].begin(); it!=nods[a].end(); it++)
{
if(dist[it->first]>dist[a]+it->second)
{
dist[it->first]=dist[a]+it->second;
if(!viz[it->first])
{
coada.push(it->first);
viz[it->first]=true;
}
}
}
}
FILE *f=fopen("bellmanford.out","w");
for(int i=2; i<=n; i++)
{
fprintf(f,"%d ",dist[i]);
}
return 0;
}