Pagini recente » Cod sursa (job #2923271) | Cod sursa (job #8207) | Cod sursa (job #2981857) | Cod sursa (job #2032116) | Cod sursa (job #1649635)
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <vector>
#include <ctype.h>
#define inf 1000000000
using namespace std;
int i,n,m,*d,lg,j,k,sw;
long long nr;
char *F;
bool o[50005];
vector< pair<int,int> > G[50005];
queue<int> Q;
void init()
{
int x,y,c;
fseek(stdin,0,SEEK_END);
lg=ftell(stdin);
rewind(stdin);
F=(char*) calloc(lg+1,sizeof(char));
fread(F,sizeof(char),lg,stdin);
for (i=0;isdigit(F[i]);i++) n=n*10+F[i]-'0';
j=i+1;
for (i=j;isdigit(F[i]);i++) m=m*10+F[i]-'0';
for (k=1;k<=m;k++)
{
x=y=c=0;
j=i+1; sw=0;
if (F[j]=='-') {sw=1; j++;}
for (i=j;isdigit(F[i]);i++) x=x*10+F[i]-'0';
if (sw) x*=-1;
j=i+1; sw=0;
if (F[j]=='-') {sw=1; j++;}
for (i=j;isdigit(F[i]);i++) y=y*10+F[i]-'0';
if (sw) y*=-1;
j=i+1; sw=0;
if (F[j]=='-') {sw=1; j++;}
for (i=j;isdigit(F[i]);i++) c=c*10+F[i]-'0';
if (sw) c*=-1;
G[x].push_back(make_pair(y,c));
}
free(F);
d=(int*) calloc(n+1,sizeof(int));
for (i=1;i<=n;i++) d[i]=inf;
}
void bellmanford(int s)
{
int i,x,y,c,z;
Q.push(s); d[s]=0; o[s]=1;
while(!Q.empty())
{
x = Q.front();
Q.pop();
o[x]=0;
z = G[x].size();
for(i=0;i<z;i++)
{
y = G[x][i].first;
c = G[x][i].second;
if(d[y] > d[x] + c)
{
d[y] = d[x] + c;
if (!o[y])
{
Q.push(y);
o[y]=1;
}
}
}
}
}
int main()
{
freopen ("dijkstra.in","r",stdin);
freopen ("dijkstra.out","w",stdout);
init();
bellmanford(1);
for (i=2;i<=n;i++)
if (d[i]==inf) printf("0 ");
else printf("%i ",d[i]);
fclose(stdin);
fclose(stdout);
return 0;
}