Cod sursa(job #1131236)

Utilizator doomaSalagean Calin dooma Data 28 februarie 2014 18:44:37
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>

using namespace std;

#define INF 0x3f3f3f3f
const int NMAX = 50001;
unsigned int N, M, Cost[NMAX];
vector< pair<int, int> > G[NMAX];

void read(){
  ifstream fin("dijkstra.in");
  fin >> N >> M;
  for(unsigned int i = 0, x, y, c; i < M; i++){
    fin >> x >> y >> c;
    G[x-1].push_back(make_pair(y-1, c));
  }
  fin.close();
}

void dijkstra(int node){
    queue<int> Q;
    int top;

    memset(Cost, INF, sizeof(Cost));

    Cost[node] = 0;

    Q.push(node);
    while(!Q.empty())
    {
        top = Q.front();

        int size = G[top].size();

        for(int i = 0; i < size; i++)
        {
            if(Cost[top] + G[top][i].second < Cost[G[top][i].first])
            {
                Cost[G[top][i].first] = Cost[top] + G[top][i].second;
                Q.push(G[top][i].first);
            }
        }
        Q.pop();
    }
}

void write(){
  ofstream fout("dijkstra.out");
  for(unsigned int i=1; i<N; i++){
    if(Cost[i] != INF){
      fout << Cost[i] << " ";
    } else {
      fout << "0 ";
    }
  }
  fout << "\n";
  fout.close();
}

int main()
{
    read();
    dijkstra(0);
    write();
    return 0;
}