Cod sursa(job #1364995)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 27 februarie 2015 22:53:31
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <cstdio>
#include <vector>
#include <queue>

#define Nmax 50005
#define DIM 1666013
#define INF 0x3f3f3f3f

using namespace std;

priority_queue<pair<int,int> > Q;
vector<vector<pair<int,int> > >G;
vector<int> DP;
int N,M;

char buffer[DIM];
int poz = DIM - 1;

void Scanf(int &A){
    A = 0;
    while('0' > buffer[poz] || buffer[poz] > '9')
        if(++poz == DIM)
            fread(buffer,1,DIM,stdin),poz = 0;
    while('0' <= buffer[poz] && buffer[poz] <= '9')
    {
        A = A * 10 + buffer[poz] - 48;
        if(++poz == DIM)
            fread(buffer,1,DIM,stdin),poz = 0;
    }
}


void Read()
{
    Scanf(N);Scanf(M);
    G.resize(N+1);
    int a,b,c;
    for(int i = 1; i <= M; ++i)
    {
        Scanf(a),Scanf(b),Scanf(c);
        G[a].push_back(make_pair(c,b));
    }
}

void Dijkstra(int k)
{
    int cost;
    DP.resize(N+1);
    DP.assign(N+1,INF);
    DP[1] = 0;
    Q.push(make_pair(0,k));
    for(int i = 1; i < N; ++i)
    {
        k = Q.top().second;
        cost = -Q.top().first;
        Q.pop();

        if(DP[k] < cost)
        {
            --i;
            continue;
        }
        for(vector<pair<int,int> >::iterator it = G[k].begin(); it != G[k].end(); ++it)
            if(DP[it->second] > DP[k] + it->first){
                DP[it->second] = DP[k] + it->first;
                Q.push(make_pair(-DP[it->second],it->second));
            }
    }
}

void Print()
{
    for(int i = 2; i <= N; ++i)
        if(DP[i] != INF)
            printf("%d ",DP[i]);
        else
            printf("0 ");
}

int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);

    Read();
    Dijkstra(1);
    Print();

    return 0;
}