Cod sursa(job #671436)

Utilizator hernameisellyBadinga Eliza hernameiselly Data 31 ianuarie 2012 14:29:44
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<fstream>
#define maxn 50001
#define inf 0x3fffffff
//const int inf=1<<30;
using namespace std;
ifstream f("dijkstra.in"); ofstream g("dijkstra.out");
struct graf {int nod, cost; graf *next;};
int n,m;
graf *a[maxn];
int d[maxn], q[maxn];
void add(int where, int what, int cost)
{graf *q = new graf;
 q->nod = what;
 q->cost = cost;
 q->next = a[where];
 a[where] = q;
}

void read()
{f>>n>>m;
 for(int x,y,z,i=1;i<=m;++i) f>>x>>y>>z,add(x, y, z); 
}
void dijkstra()
{for(int i=2;i<=n;++i) d[i]=inf;
 int minim, pminim = 0;
    for ( int i = 1; i <= n; ++i )
		{minim = inf;
        for ( int j = 1; j <= n; ++j )
            if ( d[j] < minim && !q[j] ) minim = d[j], pminim = j;
        q[pminim] = 1;
        graf *t = a[pminim];
        while ( t )
        { if ( d[ t->nod ] > d[pminim] + t->cost ) d[ t->nod ] = d[pminim] + t->cost;
            t = t->next;
        }
    }
}
int main()
{read(); dijkstra();
 for( int i = 2; i <= n; ++i ) g<<(d[i] == inf ? 0 : d[i])<<' ';
 g<<'\n'; g.close(); return 0;
}