Cod sursa(job #2498133)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 23 noiembrie 2019 15:45:16
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.72 kb
#include <bits/stdc++.h>
#define MAX 131072

using namespace std;
const int NMAX = 200010;

FILE *IN;

struct edge{
    int x, cost;
};
vector <edge> edges[NMAX];

int N, M, heapSize;
int poz[NMAX], val[NMAX], st[NMAX], heap[NMAX];
int ans[NMAX];
bool add[NMAX];

int pos, sign;
char f[MAX];

inline void Read(int &nr){
    sign = 0;
    nr = 0;
    while(f[pos] < '0' || f[pos] > '9'){
        if(f[pos] == '-') sign = 1;
        pos++;
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    while(f[pos] >= '0' && f[pos] <= '9'){
        nr = 10 * nr + f[pos++] - '0';
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    if(sign) nr =- nr;
}

void read(){
    Read(N); Read(M);
    int X, Y, Cost;
    for(int i = 1; i <= M; i++){
        Read(X); Read(Y); Read(Cost);
        edges[X].push_back({Y, Cost});
    }
}

inline Swap(int x, int y){
    swap(heap[x], heap[y]);
    poz[heap[x]] = x;
    poz[heap[y]] = y;
}

void upHeap(int node){
    int s = node / 2;
    if(val[heap[node]] < val[heap[s]] && node > 1){
        Swap(node, s);
        upHeap(s);
    }
}

void downHeap(int node){
    int s = 2 * node;
    if(s > heapSize)
        return;
    if(s < heapSize && val[heap[s]] > val[heap[s + 1]]) s++;
    if(val[heap[node]] > val[heap[s]]){
        Swap(node, s);
        downHeap(s);
    }
}

int main(){

    IN = fopen("apm.in", "r");
    freopen("apm.out", "w", stdout);

    read();
    for(int i = 1; i <= N; i++)
        val[i] = -2000;

    int Min, node, nrNodes = 0;
    for(int i = 1; i <= N; i++){
        if(heapSize > 0){
            Min = val[heap[1]];
            node = heap[1];
            Swap(1, heapSize);
            heapSize--;
            downHeap(1);
            poz[node] = 0;
        } else Min = 0, node = 1;

        add[node] = true;
        ans[node] = Min + ans[st[node]];
        for(int j = 0; j < edges[node].size(); j++){
            int z = edges[node][j].x;
            if(!add[edges[node][j].x] && val[edges[node][j].x] <= -2000){
                heapSize++;
                heap[heapSize] = edges[node][j].x;
                val[heap[heapSize]] = edges[node][j].cost;
                poz[heap[heapSize]] = heapSize;
                st[heap[heapSize]] = node;
                upHeap(heapSize);
            } else if(val[edges[node][j].x] > -2000 && val[edges[node][j].x] > edges[node][j].cost){
                val[edges[node][j].x] = edges[node][j].cost;
                st[edges[node][j].x] = node;
                upHeap(poz[edges[node][j].x]);
            }
        }
    }

    for(int i = 2; i <= N; i++)
        printf("%d ", ans[i]);


    return 0;
}

//-41801