Cod sursa(job #2681313)

Utilizator sabinandreiBocan Sabin Andrei sabinandrei Data 5 decembrie 2020 11:32:28
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
// Dijkstra.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

#define INF 2000000000

using namespace std;

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

int n;
int d[50001], inq[50001];

struct arc
{
    int x, y, c;
};

vector<arc> G[50001];

struct compara
{
    bool operator()(int x, int y)
    {
        return d[x] > d[y];
    }
};

priority_queue<int, vector<int>, compara> q;

void read()
{
    int m, i, x;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        arc u;
        fin >> x >> u.y >> u.c;
        G[x].push_back(u);
    }
}

void solve(int r)
{
    int k, y, c, lg, i;
    for (i = 1; i <= n; i++)
        d[i] = INF;
    d[r] = 0;

    q.push(r);
    inq[r] = 1;

    while (!q.empty())
    {
        k = q.top();
        q.pop();

        inq[k] = 0;
        for (i = 0; i < G[k].size(); i++)
        {
            y = G[k][i].y;
            c = G[k][i].c;
            lg = d[k] + c;
            if (lg < d[y])
            {
                d[y] = lg;
                if (inq[y] == 0)
                {
                    q.push(y);
                    inq[y] = 1;
                }
            }
        }
    }
    for (i = 2; i <= n; i++)
    {
        if (d[i] != INF)
            fout << d[i] << " ";
        else
            fout << 0 << " ";
    }
}

int main()
{
    read();
    solve(1);
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started: 
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file