Cod sursa(job #1164650)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 2 aprilie 2014 11:13:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "dijkstra.in";
const char outfile[] = "dijkstra.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;

typedef vector<pair<int, int> > Graph[MAXN];
typedef vector<pair<int, int> > :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

const int lim = (1 << 20);
char buff[lim];
int pos;

inline void get(int &x) {
    x = 0;
    while(!('0' <= buff[pos] && buff[pos] <= '9'))
        if(++ pos == lim) {
            fread(buff, 1, lim, stdin);
            pos = 0;
        }
    while('0' <= buff[pos] && buff[pos] <= '9') {
        x = x * 10 + buff[pos] -'0';
        if(++ pos == lim) {
            fread(buff, 1, lim, stdin);
            pos = 0;
        }
    }
}

int dp[MAXN], N, M;
Graph G;

inline void Dijkstra(Graph &G, int Source) {
    priority_queue<pair<int, int> , vector <pair<int, int> > , greater <pair<int, int> > > Q;
    memset(dp, oo, sizeof(dp));
    dp[Source] = 0;
    Q.push(make_pair(0, Source));
    while(!Q.empty()) {
        int Node = Q.top().second;
        int cst = Q.top().first;
        Q.pop();
        if(dp[Node] < cst)
            continue;
        for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
            if(dp[it->first] > dp[Node] + it->second) {
                dp[it->first] = dp[Node] + it->second;
                Q.push(make_pair(dp[it->first], it->first));
            }
    }
    for(int i = 2 ; i <= N ; ++ i) {
        if(dp[i] == oo)
            dp[i] = 0;
        fout << dp[i] << ' ';
    }
    fout << '\n';
}

int main() {
    freopen(infile, "r", stdin);
    get(N);
    get(M);
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y, z;
        get(x); get(y); get(z);
        G[x].push_back(make_pair(y, z));
    }
    Dijkstra(G, 1);
    fout.close();
    return 0;
}