Cod sursa(job #2543754)

Utilizator Horia14Horia Banciu Horia14 Data 11 februarie 2020 14:51:19
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include<cctype>
#include<vector>
#include<cstdio>
#include<queue>
#define oo 1000000000
#define MAX_V 50000
#define BUF_SIZE 1 << 18
using namespace std;
vector<pair<int, int>>g[MAX_V + 1];
int dist[MAX_V + 1], n, m, pos = BUF_SIZE;
char buf[BUF_SIZE];

inline char getChar(FILE* fin) {
    if(pos == BUF_SIZE) {
        fread(buf, 1, BUF_SIZE, fin);
        pos = 0;
    }
    return buf[pos++];
}

inline int read(FILE* fin) {
    int res = 0;
    char c;
    do {
        c = getChar(fin);
    }while(!isdigit(c));
    do {
        res = 10*res + c - '0';
        c = getChar(fin);
    }while(isdigit(c));
    return res;
}


class ComparVf {
public:
    bool operator() (const int& x, const int& y) {
        return dist[x] > dist[y];
    }
};

priority_queue<int, vector<int>, ComparVf> H;

void readGraph() {
    FILE* fin = fopen("dijkstra.in", "r");
    int x, y, c;
    n = read(fin);
    m = read(fin);
    for(int i = 1; i <= m; i++) {
        x = read(fin); y = read(fin); c = read(fin);
        g[x].push_back(make_pair(y, c));
        //printf("%d %d %d\n", x, y, c);
    }
    fclose(fin);
}

void Dijkstra(int source) {
    int i, vfmin;
    for(i = 1; i <= n; i++) {
        dist[i] = oo;
    }
    dist[source] = 0;
    H.push(source);
    while(!H.empty()) {
        vfmin = H.top();
        H.pop();
        for(auto j : g[vfmin]) {
            if(dist[j.first] > dist[vfmin] + j.second) {
                dist[j.first] = dist[vfmin] + j.second;
                H.push(j.first);
            }
        }
    }
}

void printDistances() {
    FILE* fout = fopen("dijkstra.out", "w");
    for(int i = 2; i <= n; i++)
        if(dist[i] == oo)
            fprintf(fout,"0 ");
        else fprintf(fout, "%d ",dist[i]);
    fprintf(fout,"\n");
    fclose(fout);
}

int main() {
    readGraph();
    Dijkstra(1);
    printDistances();
    return 0;
}