Cod sursa(job #2347018)

Utilizator ImbuzanRaduImbuzan Radu ImbuzanRadu Data 18 februarie 2019 12:24:25
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n, m, mindist[50005];
vector<pair<int, int> >adj[50005];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >pq;
bool viz[50000];

void dijkstra(int nod)
{
  viz[nod] = 1;
  pq.push(make_pair(1, 0));
  while(!pq.empty())
  {
    pair<int, int> p = pq.top();
    pq.pop();

     if(mindist[p.first] != p.second)
      continue;

    viz[p.first] = 1;

    for(auto i : adj[p.first])
    {
      if(mindist[i.first] > p.second + i.second && viz[i.first] == 0)
      {
        mindist[i.first] = p.second + i.second;
        pq.push({i.first, mindist[i.first]});
      }
    }
  }
}

int main()
{
    f>>n>>m;
    int x, y, cost;
    for(int i = 1; i <= m; i++)
    {
      f>>x>>y>>cost;
      adj[x].push_back({y, cost});
    }

    for(int i = 1; i <= n; i++)
      mindist[i] = 0x3f3f3f3f;

    mindist[1] = 0;

    dijkstra(1);

    for(int i = 2; i <= n; i++)
      if(viz[i] != 0)
        g<<mindist[i]<<" ";
      else g<<0<<" ";
    return 0;
}