Cod sursa(job #2342762)

Utilizator victorv88Veltan Victor victorv88 Data 13 februarie 2019 12:43:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

int n, m, from, to, cost,dp[50005];

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

class cmp{
public:
    bool operator () (pair<int,int>a,pair<int,int>b)
    {
        return a.second>b.second;
    }
};

vector<pair<int,int>>graph[50005];
priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>q;

bool viz[50005];

void solve()
{
    q.push({1,0});
    while (!q.empty())
    {
        pair<int,int>node=q.top();
        q.pop();
        viz[node.first]=false;
        for (auto &v:graph[node.first])
        {
            if (dp[node.first]+v.second<dp[v.first])
            {
                dp[v.first]=dp[node.first]+v.second;
                if (viz[v.first]==false)
                 q.push({v.first,dp[v.first]}),viz[v.first]=true;
            }
        }
    }

}

int main() {
    f >> n >> m;
    for (int i=2; i<=n; i++)
    {
        dp[i]=0x3f3f3f3f;
    }
    for (int i=1; i<=m; ++i)
    {
        f >> from >> to >> cost;
        graph[from].push_back({to,cost});
    }
    solve();
    for (int i=2; i<=n; i++)
    {
        if (dp[i]==0x3f3f3f3f)
            g << 0 <<' ';
        else
            g << dp[i] <<' ';
    }
    return 0;
}