Cod sursa(job #2933900)

Utilizator MacraAlexandruMacra Alexandru MacraAlexandru Data 5 noiembrie 2022 13:36:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int oo=(1<<30);
int n, m, p, d[100001], viz[100001];
vector <pair<int, int>> v[100001];
queue<int> q;
priority_queue<pair<int, int>> Q;
void citire()
{
    int x, y, dst;
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        f>>x>>y>>dst;
        v[x].push_back(make_pair(y, dst));
    }
}
void afis()
{
    for(int i=2; i<=n; i++)
    {
        if(d[i]==INT_MAX)g<<"0 ";
        else g<<d[i]<<" ";
    }
}
/*void BellmanFord(int p)
{
    for(int i=1; i<=n; i++)d[i]=-1;
    d[p]=0;
    viz[p]=1;
    q.push(p);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        viz[x]=0;
        for(auto i:v[x])
        {
            int vcn=i.first, cst=i.second;
            if(d[vcn]==-1 || d[x]+cst<d[vcn])
            {
                d[vcn]=d[x]+cst;
                if(!viz[vcn])
                {
                    q.push(vcn);
                    viz[vcn]=1;
                }
            }
        }
    }
    afis();
}*/
void Dijkstra(int p)
{
    for(int i=1; i<=n; i++)d[i]=INT_MAX;
    d[p]=0;
    Q.push({0, p});
    while(!Q.empty())
    {
        int x=Q.top().second;
        Q.pop();
        if(viz[x])continue;
        viz[x]=1;
        for(auto i:v[x])
        {
            int vcn=i.first, cst=i.second;
            if(d[x]+cst<d[vcn])
            {
                d[vcn]=d[x]+cst;
                if(!viz[vcn])Q.push({-d[vcn], vcn});
            }
        }
    }
    afis();
}
int main()
{
    citire();
    Dijkstra(1);
    return 0;
}