Cod sursa(job #2198508)

Utilizator cristiP97Prodan Cristian cristiP97 Data 24 aprilie 2018 16:09:33
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <iostream>
#include <queue>

using namespace std;
ifstream in("dijkstra.in");

struct comp {
    bool operator()(pair <int, int> &a, pair <int, int> &b) {
        return a.second > b.second;
    }
};

const int knmax = 50005;
const int INF = 999999999;
vector <pair <int,int> > adj[knmax];
int d[knmax];
priority_queue<pair <int, int> ,vector <pair <int,int> >, comp> PQ;

void citire(int m){

    int nod1,nod2,cost;
    for(int i = 1; i<= m; ++i) {
        in >> nod1 >> nod2 >> cost;
        adj[nod1].push_back(make_pair(nod2,cost));
    }
}

int main() {
    int n,m;
    in >> n >> m;

    citire(m);
    in.close();
    
   /* cout << n << " " <<  m << '\n';
    
    for(int i = 1; i <=n; ++i) {
        for(int j = 0; j < adj[i].size(); ++j) {
            cout << adj[i][j].first << " " << adj[i][j].second << " ";
        }
        cout << endl;
    }
    
    cout << endl;*/
    
    d[1] = 0;
    
    for(int i = 2; i <= n; ++i) {
        d[i] = INF;
    }
    
    PQ.push(make_pair(1,0));
    
    while(!PQ.empty()) {
       pair <int,int> pereche;
       pereche = PQ.top();
       PQ.pop();
       
       if(d[pereche.first] < pereche.second)
            continue;
       
       for(int j = 0; j < adj[pereche.first].size(); ++j) {
            int v = adj[pereche.first][j].first;
            int cost = adj[pereche.first][j].second;
            if(d[v] > d[pereche.first] + cost){
                d[v] = d[pereche.first] + cost;
                PQ.push(make_pair(v, d[v]));
            }
       }
    }
    
	ofstream out("dijkstra.out");
    for(int i = 2; i <= n ; ++i ){
		if(i == n)
			out << d[i];
		else
			out << d[i] << " ";
    }
    
    
    
    
    
    
    return 0;
}