Cod sursa(job #1192608)

Utilizator CostinVFMI CostinVictorGabriel CostinV Data 29 mai 2014 13:25:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include<fstream>
#include<vector>
#include<queue>

#define inf 99999

using namespace std;

vector<pair<int, int> > *g;
vector<int> d, p;
queue <int> q;

int n, m, x, y, z, curent;

void dijkstra()
{
    d[0] = 0;

    q.push(0);
    while(!q.empty())
    {
        curent = q.front();
        q.pop();

        for(int i=0; i<g[curent].size(); i++)
        {
            if(d[curent] + g[curent][i].second < d[g[curent][i].first])
            {
                //p[g[curent][i].first] = curent;
                d[g[curent][i].first] = d[curent] + g[curent][i].second;

                q.push(g[curent][i].first);
            }
        }
    }
}

int main()
{
    ifstream f("dijkstra.in");

    f>>n>>m;
    g = new vector<pair<int, int> > [n];

    for(int i=0; i<m; i++)
    {
        f>>x>>y>>z;
        g[x-1].push_back(pair<int, int>(y-1, z));
    }

    for(int i=0; i<n; i++)
    {
        d.push_back(inf);
        //p.push_back(0);
    }

    dijkstra();

    ofstream g("dijkstra.out");
    for(int i = 1; i<n; i++)
        if(d[i]==inf)
            g<<0<<" ";
        else
            g<<d[i]<<" ";

    return 0;
}