Cod sursa(job #2478295)

Utilizator RedXtreme45Catalin RedXtreme45 Data 21 octombrie 2019 20:53:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 50010
#define INF 0x3f3f3f3f

using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct NodCost {
  int nod, cost;
  bool operator < (const NodCost& other) const {
    return cost > other.cost;
  }
};

vector<NodCost> G[NMAX];
long long int dist[NMAX];
priority_queue<NodCost> q;
int n;

void dijkstra(int start) {
	memset (dist, INF, sizeof dist);

	dist[start] = 0;
  	q.push({start, 0});
  	while(!q.empty()) {
      int nod = q.top().nod;
      int cost = q.top().cost;
      q.pop();

      if(cost != dist[nod]) continue;
      for(auto vec : G[nod]) {
        if(dist[vec.nod] > cost + vec.cost) {
          dist[vec.nod] = cost + vec.cost;
          q.push({vec.nod, dist[vec.nod]});
        }
      }
    }

}
int main()
{
    int n,a,b,i,c,m;
    fin>>n>>m;
    for (i=1;i<=m;i++)
    {
        fin>>a>>b>>c;
        G[a].push_back({b,c});
    }
    dijkstra(1);
    for (i=2;i<=n;i++)
    {
        if (dist[i]<INF)
            fout<<dist[i]<<" ";
        else
            fout<<0<<" ";
    }
        fin.close();
        fout.close();
    return 0;
}