Pagini recente » Cod sursa (job #1958388) | Cod sursa (job #2960903) | Cod sursa (job #743682) | Cod sursa (job #1266763) | Cod sursa (job #520793)
Cod sursa(job #520793)
#include <fstream>
#include <queue>
#define nmax 50002
#define oo 0x3f3f3f3f
using namespace std;
queue <int> Q;
int n,m;
bool viz[nmax];
struct nod{
int inf,cost;
nod *urm;
} *g[nmax];
int dist[nmax];
void add(int x,int y,int z)
{
nod *aux = new nod;
aux->inf = y;
aux->cost = z;
aux->urm = g[x];
g[x] = aux;
}
int main()
{
ifstream f("dijkstra.in");
ofstream gg("dijkstra.out");
f>>n>>m;
int x,y,z;
for(int i=1;i<=m;i++)
{
f>>x>>y>>z;
add(x,y,z);
}
dist[1] = 0;
Q.push(1);
viz[1] = true;
for(int i=2;i<=n;i++)
dist[i] = oo;
while(! Q.empty()){
int nd = Q.front();
Q.pop();
viz[nd]=false;
for(nod *p=g[nd];p;p=p->urm)
{
int t=p->inf;
if(dist[nd] + p->cost < dist[t])
{
dist[p->inf] = p->cost + dist[nd];
if(!viz[t])
{
Q.push(t);
viz[t]=true;
}
}
}
}
for(int i=2;i<=n;i++)
if(dist[i] == oo)
gg<<0<<" ";
else
gg<<dist[i]<< " ";
return 0;
}