Cod sursa(job #2875793)

Utilizator fastlikearabbitDaniel Ghenghea fastlikearabbit Data 22 martie 2022 12:44:18
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include<limits.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int NMAX = 50005;
int N, M, startNode = 1;
int oo = INT_MAX;

vector<pair<int, int>> adj[NMAX];
int distances[NMAX];
bool visited[NMAX];
queue< pair<int, int> > q;

void read() {
    fin >> N >> M;
    
    for(int i = 1; i <= M; i++) {
        int from, to, weight;
        
        fin >> from >> to >> weight;
        adj[from].push_back(make_pair(to, weight));
    }
    
    for(int i = 2; i <= N; i++)
        distances[i] = oo;
    
    for(int i = 2; i <= N; i++)
        visited[i] = false;
}

void solve() {
    q.push(make_pair(startNode, 0));
    
    while(!q.empty()) {
        pair<int,int> currentNode = q.front();
        q.pop();
        //int node = currentNode.first;
        //int weight = currentNode.second;
        
        if (visited[currentNode.first]) continue;
        visited[currentNode.first] = true;
        
        for(auto neighbour: adj[currentNode.first]) {
            if(distances[neighbour.first] > distances[currentNode.first] + neighbour.second)
                distances[neighbour.first] = distances[currentNode.first] + neighbour.second;
            
            q.push(make_pair(neighbour.first, distances[neighbour.first]));
            
        }
        
    }
    }

void write() {
    for(int i = 2; i <= N; i++)
        fout << distances[i] << " ";
}

int main() {
    read();
    solve();
    write();
    
    //cout << oo;
    
    return 0;
}