Cod sursa(job #2198509)

Utilizator cristiP97Prodan Cristian cristiP97 Data 24 aprilie 2018 16:25:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 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();
    
    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(unsigned 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) {
			if(d[i] == INF)
				out << "0";
			else
				out << d[i];
		}
		else {
			if(d[i] == INF)
				out << "0" << " ";
			else
				out << d[i] << " ";
		}
    }
    out.close();
 
    
    return 0;
}