Cod sursa(job #2353957)

Utilizator UnseenMarksmanDavid Catalin UnseenMarksman Data 24 februarie 2019 19:08:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;

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

const int maxn = 5e4+2;
const int inf= 2e9;
int n, m, cost[maxn];
bool viz[maxn];

struct str{
    int x;
    bool operator <(const str &other)const
    {
        return cost[x]>cost[other.x];
    }
};
vector<pair<int, int> >G[maxn];
priority_queue<str>H;

void dijkstra()
{
    cost[1]=0;
    for(int i=2; i<=n; i++)
    {
        cost[i]=inf;
    }
    H.push({1});
    viz[1]=true;
    while(!H.empty())
    {
        str t=H.top();
        H.pop();
        viz[t.x]=false;
        for(auto it:G[t.x])
        {
            if(cost[it.first]>it.second+cost[t.x])
            {
                cost[it.first]=it.second+cost[t.x];
                if(!viz[it.first])
                {
                    viz[it.first]=true;
                    H.push({it.first});
                }
            }
        }
    }
}

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