Cod sursa(job #3294035)

Utilizator TeogaloiuMatei Ionescu Teogaloiu Data 15 aprilie 2025 11:38:54
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");
struct heapNode
{
    int node;
    int val=0;
    bool operator <(const heapNode &a) const{
        return val>a.val;
    }
};
vector <heapNode> v[50001];
int ans[50001];
void addtopq(priority_queue <heapNode> &pq,int Node,int csf)///*cost so far*///
{
    for(int i=0;i<v[Node].size();i++) {
        heapNode neighbour = v[Node][i];
        if(ans[neighbour.node]>neighbour.val+csf){
            ans[neighbour.node]=neighbour.val+csf;
            pq.push({neighbour.node,neighbour.val+csf});
        }
    }
}
void dijkstra()
{
    priority_queue <heapNode> pq;
    pq.push({1,0});
    ans[1]=0;
    int cost=0;
    while(!pq.empty())
    {
        heapNode current=pq.top();
        pq.pop();
        //ans[current.pointer]=current.val;
        addtopq(pq,current.node,current.val);
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        ans[i]=1000000000;
    for(int i=1;i<=m;i++)
    {
        int a,b,c;
        cin>>a>>b>>c;
        v[a].push_back({b,c});
        v[b].push_back({a,c});
    }
    dijkstra();
    for(int i=2;i<=n;i++)
        cout<<ans[i]<<' ';
    return 0;
}