Cod sursa(job #2097904)

Utilizator vlad.ulmeanu30Ulmeanu Vlad vlad.ulmeanu30 Data 1 ianuarie 2018 21:01:11
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
#define inf 20005
#define maxn 50000

using namespace std;

vector <int> v[maxn]; /// vecini
vector <int> len[maxn]; /// lungime muchie
int cost[maxn]; /// cost minim
bool viz[maxn]; /// nod vizitat
int coada[maxn]; /// coada

int main ()
{
  ifstream fin ( "dijkstra.in" );
  ofstream fout ( "dijkstra.out" );

  int n, m;

  fin >> n >> m; /// noduri, arce

  int i, a, b, l;

  for ( i = 0; i < m; i++ )
  {
    fin >> a >> b >> l;

    a--;
    b--;

    v[a].push_back ( b );
    v[b].push_back ( a );

    len[a].push_back ( l );
    len[b].push_back ( l );
  }

  for ( i = 1; i < n; i++ )
    cost[i] = inf;

  int j, x;
  int nv; /// nr de vecini

  int pr = 0, ul = 0; /// capetele cozii

  coada[0] = 0;

  while ( pr <= ul )
  {
    x = coada[pr];
    if ( viz[x] == false )
    {
      viz[x] = true;
      nv = v[x].size ();

      for ( j = 0; j < nv; j++ )
      {
        if ( cost[x] + len[x][j] < cost[ v[x][j] ] )
          cost[ v[x][j] ] = cost[x] + len[x][j];

        if ( viz[ v[x][j] ] == false )
          coada [ ++ul ] = v[x][j];
      }
    }
    pr++;
  }

  for ( i = 1; i < n; i++ )
    if ( cost[i] < inf )
      fout << cost[i] << ' ';
    else
      fout << "0 ";

  fin.close ();
  fout.close ();

  return 0;
}