Cod sursa(job #2505859)

Utilizator razvanradulescuRadulescu Razvan razvanradulescu Data 7 decembrie 2019 11:30:26
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <iostream>
#include <set>
#include <vector>
#include <string.h>
using namespace std;

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

const int INF = 0x3f3f3f3f;

int cost[50005], n, m;

struct vecin
{
    int info, c;
    bool operator< (const vecin& other) const
    {
        if(c == other.c)
            return info < other.info;
        return c < other.c;
    }
};
vector<vecin> nod[50005];
set<vecin> S;

void citire()
{
    f>>n>>m;
    int x, y, c;
    for(int i = 0; i<m; ++i)
    {
        f>>x>>y>>c;
        nod[x].push_back({y, c});
    }
    for(int i = 2; i<=n; ++i)
        cost[i] = INF;
}

void dijkstra()
{
    S.insert({1, 0});
    while(!S.empty())
    {
        int currNod = S.begin()->info;
        S.erase(S.begin());

        for(auto p : nod[currNod])
        {
            if(cost[p.info] > cost[currNod] + p.c)
            {
                if(cost[p.info] != INF)
                    S.erase({p.info, cost[p.info]});
                cost[p.info] = cost[currNod] + p.c;
                S.insert({p.info, cost[p.info]});
            }
        }
    }
}

int main()
{
    citire();
    dijkstra();
    for(int i = 2; i<=n; ++i)
    {
        if(cost[i] == INF)
            g<<0<<" ";
        else
            g<<cost[i]<<" ";
    }
    return 0;
}