Cod sursa(job #1786709)

Utilizator enescu_rEnescu Radu enescu_r Data 23 octombrie 2016 15:14:02
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 50005;

struct GNode
{
    int node, cost;
};

struct QNode
{
  int node, cost;
  bool operator < (const QNode &x) const
  {
      return cost > x.cost;
  }
};

priority_queue <QNode> Q;
vector <GNode> G[MAXN];
vector <GNode> :: iterator it;
int D[MAXN];
int N, M, i, x, y, c;

void Dijkstra(int x)
{
    int d, nod, cos;
    Q.push({x, 0});
    while (Q.empty() == 0)
    {
        nod = Q.top().node;
        cos = Q.top().cost;
        Q.pop();
        if (D[nod] == cos)
            for (it = G[nod].begin(); it!= G[nod].end(); ++it)
            {
                d = D[nod] + it->cost;
                if (d < D[it->node])
                {
                    D[it->node] = d;
                    Q.push({it->node, d});
                }
            }
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    scanf("%d%d\n",&N, &M );
    for (i = 2; i <= N; ++i)
      D[i] = INF;
    for (i = 0; i < M; ++i) {
      scanf("%d%d%d", &x, &y, &c);
      G[x].push_back({y, c});
    }
    Dijkstra(1);
    for (i = 2; i <= N; ++i)
      if(D[i] == INF) printf("0 ");
      else
            printf("%d ", D[i]);
    printf("\n");
    return 0;
}