Cod sursa(job #1251224)

Utilizator angelaAngela Visuian angela Data 29 octombrie 2014 06:13:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>
#include <queue>
#include <bitset>
using namespace std;
 
const int Nmax = 50000, Inf = 1 << 30;
 
struct Edge {
    int node, cost;
    const bool operator < (const Edge &other) const 
    {
        return cost > other.cost;
    }
};
 
vector <Edge> G[Nmax + 5];
priority_queue <Edge> Q;
vector<int> d;
int n; 
bitset<Nmax + 5> v;
 
void Dijkstra (int k) 
{
    d = vector<int>(n + 1, Inf);
    
    d[1] = 0;
    Q.push({k, 0});
    
    while (!Q.empty() ) 
    {
        k = Q.top().node;
        v[k] = 1;    // cost minim final pentru k (nu tebuie sa mai intre in coada)
        for (auto x : G[k])
            if(!v[x.node] && d[k] + x.cost < d[x.node]) 
            {
                d[x.node] = d[k] + x.cost;
                Q.push({x.node, d[x.node]});
            }
        while (!Q.empty() && v[Q.top().node])
            Q.pop();
    }
}
 
int main() 
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    int a, b, c, m;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++) 
    {
        scanf("%d%d%d", &a, &b, &c);
        G[a].push_back({b, c});
    }
 
    Dijkstra(1);
 
    for (int i = 2; i <= n; i++) 
    {
        if (d[i] == Inf)
            d[i] = 0;
        printf("%d ", d[i]);
    }
    return 0;
}