Cod sursa(job #1513901)

Utilizator andreiblajdevAndrei Blaj andreiblajdev Data 30 octombrie 2015 10:44:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define nmax 50001
#define inf 1<<30

using namespace std;

ifstream fi("dijkstra.in");
ofstream fo("dijkstra.out");

int n, m;
int cost[nmax];
vector < pair<int, int> > G[nmax];
queue < pair<int, int> > q;

void read();
void dijkstra();
void write();

int main()
{
    
    read();
    dijkstra();
    write();
    
    fi.close();
    fo.close();
    
    return 0;
}

void read()
{
    int a, b, c;
    
    fi >> n >> m;
    
    for (int i = 1; i <= m; i++)
    {
        fi >> a >> b >> c;
        G[a].push_back(make_pair(b, c));
    }
}

void dijkstra()
{
    
    q.push(make_pair(1, 0)); // nod, cost de la nodul 1 pana in nodul respectiv
    
    for (int i = 2; i <= n; i++)
        cost[i] = inf;
    
    while (!q.empty())
    {
        
        int nodCurent = q.front().first;
        int costCurent = q.front().second;
        
        q.pop();
        
        for (int i = 0 ; i < G[nodCurent].size(); i++)
        {
            int vecin = G[nodCurent][i].first;
            int costMuchie = G[nodCurent][i].second;
            
            if (costCurent + costMuchie < cost[vecin])
            {
                cost[vecin] = costCurent + costMuchie;
                q.push(make_pair(vecin, cost[vecin]));
            }
        }
        
    }
    
}

void write()
{
    for (int i = 2; i <= n; i++)
    {
        if (cost[i] == inf)
            cost[i] = 0;
        fo << cost[i] << " ";
    }
}