Cod sursa(job #520787)

Utilizator mytzuskyMihai Morcov mytzusky Data 10 ianuarie 2011 12:58:37
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include<fstream>
#include <queue>

#define nmax 50002
#define oo 0x3f3f3f3f

using namespace std;

queue <int> Q;

int n,m;
int viz[nmax];

struct nod{
    int inf,cost;
    nod *urm;
};
nod *g[nmax];

struct vec{
    int dist;
};
vec v[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);
    }
    v[1].dist = 0;
    Q.push(1);
    viz[1] = 1;
    for(int i=2;i<=n;i++)
        v[i].dist = oo;

    while(! Q.empty()){
        int nd = Q.front();
        Q.pop();

        viz[nd]=0;
        for(nod *p=g[nd];p;p=p->urm)
        {

            int t=p->inf;

            if(v[nd].dist + p->cost < v[t].dist)
            {
                v[t].dist = p->cost + v[nd].dist;

                if(viz[t] == 0)
                {
                    Q.push(t);
                    viz[t]=1;
                }
            }
        }
    }

    for(int i=2;i<=n;i++)
        if(v[i].dist == oo)
            gg<<0<<" ";
        else
            gg<<v[i].dist<< " ";


    return 0;
}