Cod sursa(job #1138454)

Utilizator xoSauceSergiu Ferentz xoSauce Data 10 martie 2014 01:58:52
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <vector>
#include <cstdio>
#include <memory.h>
#include <queue>
#define lim 50009

using namespace std;


int n,m;
const int oo = (1<<30)-1;
struct node{

	int index;
	int cost;
};

bool viz[lim];
int cost[lim];
vector<pair<int,int> >v[lim];
struct orderByCost{

  bool operator() (node const &a, node const &b) { return a.cost > b.cost; }
};

priority_queue <pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > >Q;
void read(){

	scanf("%d %d",&n,&m);
	int x,y,c;
	for(int i = 0 ; i < m; i++){
	  scanf("%d %d %d",&x,&y,&c);

	  v[x].push_back(make_pair(y,c));
	}
}

void initialize(int start){
  
  for(int i = 1; i <= n; i++)
    cost[i] = oo;  
  
  memset(viz,0,sizeof viz);
  cost[start] = 0;
}

void dijkstra(int start){
  
  initialize(start);
  pair<int,int> currentNode;
  currentNode . second = 0;
  currentNode . first  = 1;
  Q.push(currentNode);
  viz[start] = true;
  while(!Q.empty()){
    
    currentNode = Q.top();
    Q.pop();
    pair<int,int> nextNode;
      for(unsigned int i = 0 ; i < v[currentNode.first].size();i++){
	   
	  nextNode = v[currentNode.first][i];
	  if(!viz[nextNode.first]){
	  int newCost = nextNode.second + cost[currentNode.first];
	    if(cost[nextNode.first] > newCost){
	      cost[nextNode.first] = newCost;
	      Q.push(nextNode);
	    }
	  }

	}
	viz[start]=true;
    
  }
  
}


void print(){
    for(int i = 2; i <= n; i++){
      if(cost[i] == oo)
	printf("0 ");
      else
      printf("%d ",cost[i]);
      
    }
    printf("\n");
}
int main(){
      
      freopen("dijkstra.in","r",stdin);
      freopen("dijkstra.out","w",stdout);
      read();
      dijkstra(1);
      print();
      return 0;
}