Cod sursa(job #2191189)

Utilizator Horia14Horia Banciu Horia14 Data 1 aprilie 2018 22:54:47
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
//Dijkstra O(n^2 + m) = O(n^2)

#include<cstdio>
#include<vector>
#include<cctype>
#define MAX_N 50000
#define BUF_SIZE 1 << 18
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int,int> >g[MAX_N + 1];
int dist[MAX_N + 1], n, m, pos = BUF_SIZE;
bool used[MAX_N + 1];
char buf[BUF_SIZE];

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

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;
}

void readGraph() {
    int x, y, cost;
    FILE* fin = fopen("dijkstra.in","r");
    n = read(fin);
    m = read(fin);
    for(int i = 0; i < m; i++) {
        x = read(fin);
        y = read(fin);
        cost = read(fin);
        g[x].push_back(make_pair(y,cost));
    }
    fclose(fin);
}

void Dijkstra(int node) {
    vector<pair<int,int> >::iterator it;
    int i, j, minNode;
    for(i = 0; i <= n; i++)
        dist[i] = oo;
    dist[node] = 0;
    for(i = 1; i <= n; i++) {
        minNode = 0;
        for(j = 1; j <= n; j++)
            if(!used[j] && dist[j] < dist[minNode])
                minNode = j;
        used[minNode] = true;
        for(it = g[minNode].begin(); it != g[minNode].end(); it++)
            if(dist[(*it).first] > dist[minNode] + (*it).second)
                dist[(*it).first] = dist[minNode] + (*it).second;
    }
}

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

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