Cod sursa(job #3244090)

Utilizator Dragu_AndiDragu Andrei Dragu_Andi Data 23 septembrie 2024 15:57:46
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int maxN=50005, inf=21000;
int n, m;

struct Node{
    int nod;
    long long cost;
    bool operator < (const Node &other) const{
        return cost > other.cost;
    }
};

long long dist[maxN];
vector<Node> G[maxN];
priority_queue<Node> heap;

void dijkstra(int start)
{
    for(int i=1; i<=n; i++)
        dist[i]=inf;
    dist[start]=0;
    heap.push({start, 0});
    while(!heap.empty())
    {
        Node top=heap.top();
        heap.pop();
        if(dist[top.nod]<top.cost)
        {
            continue;
        }
        for(auto vecin : G[top.nod])
        {
            if(dist[top.nod] + vecin.cost < dist[vecin.nod])
            {
                dist[vecin.nod]= dist[top.nod] + vecin.cost;
                heap.push({vecin.nod, dist[vecin.nod]});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    int x, y, c;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
    dijkstra(1);
    for(int i=2; i<=n; i++)
    {
        if(dist[i]==inf)
            dist[i]=0;
        fout << dist[i] << ' ';
    }
    return 0;
}