Cod sursa(job #2661192)

Utilizator AlexutAlex Calinescu Alexut Data 21 octombrie 2020 16:09:35
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;

int costuri[50005];
struct cmp
{
    bool operator()(const int a, const int b)
    {
        return costuri[a]<costuri[b];
    }
};
vector< pair<int,int> > v[50005];
priority_queue<int, vector<int>, cmp> pq;
int viz[500005];
void dijk(int a)
{
    pq.push(a);
    while(!pq.empty())
    {
        int top=pq.top();
        pq.pop();
        if(viz[top]==0)
        {
            for(int i=0; i<v[top].size(); i++)
            {
                if(costuri[v[top][i].first]>costuri[top]+v[top][i].second)
                {
                    costuri[v[top][i].first]=costuri[top]+v[top][i].second;
                    pq.push(v[top][i].first);
                }
            }
            viz[top]=1;
        }
    }
}
int main()
{

    ifstream cin ("dijkstra.in");
    ofstream cout ("dijkstra.out");
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int m,n,i,j,x,y;
    cin>>n>>m;
    for(i=1; i<=m; i++)
    {
        int cost;
        cin>>x>>y>>cost;
        v[x].push_back(make_pair(y,cost));
    }
    for(i=1; i<=n; i++)
        costuri[i]=INT_MAX;
    costuri[1]=0;
    dijk(1);
    for(i=2; i<=n; i++)
    {
        if(costuri[i]==INT_MAX)
            costuri[i]=0;
        cout<<costuri[i]<<" ";
    }
    return 0;
}