Cod sursa(job #1253150)

Utilizator xoSauceSergiu Ferentz xoSauce Data 31 octombrie 2014 20:38:57
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <queue>
#include <cstdio>
#include <limits>
using namespace std;


struct node{
     int cost;
     int at;
};

vector<vector<node>> v;
int cost[50010];
bool visited[50010];
struct smaller_first{
     
     bool operator()(const int a, const int b){
          return cost[a] > cost[b];
     }
};

void solve(int start){
     
     priority_queue<int,vector<int>,smaller_first> pq;
     cost[start] = 0;
     pq.push(start);
     while(!pq.empty()){
          int current_node = pq.top();
          pq.pop();
          for(int i =0 ; i < v[current_node].size(); i++){
	node next_node = v[current_node][i];
	if(!visited[next_node.at]){
	     if(cost[next_node.at] > cost[current_node] + next_node.cost){
	          cost[next_node.at] = cost[current_node] + next_node.cost;
	          pq.push(next_node.at);
	     } 
	}
          }
          visited[current_node] = true;
     }
}

int main(){
     
     
     int n,m;
     freopen("dijkstra.in","r",stdin);
     freopen("dijkstra.out","w",stdout);
     scanf("%d %d",&n,&m);
     for(int i =0 ; i <= n; i++){
          v.push_back(vector<node>());
     }
     for(int i = 0; i < m;i++){
          int x,y,c;
          scanf("%d %d %d",&x,&y,&c);
          node k;
          k.cost = c;
          k.at = y;
          v[x].push_back(k);          
     }
     for(int i = 0 ;i <= n;i++){
          cost[i] = numeric_limits<int>::max();
     }
     solve(1);
     for(int i = 2; i <= n;i ++){
          if(cost[i] == numeric_limits<int>::max())
	printf("0 ");
          else
	printf("%d ", cost[i]);
     }
     printf("\n");
     return 0;
}