Cod sursa(job #2696301)

Utilizator VarothexVartic Mihai-Vlad Varothex Data 15 ianuarie 2021 17:56:56
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
 
vector<pair<int, int> > graf[100005];
priority_queue<pair<int, int> > pq;
bool vis[100005];
int dist[100005], n, m, t_cost;
 
void dijkstra(int start) 
{
 
    dist[start] = 0;
    pq.push({0, start});
    for (int i = 1; i <= n; i++) 
	{
        if (i != start) 
		{
            dist[i] = 1e9;
            vis[i] = false;
        }
    }
 
    while (!pq.empty()) 
	{
        int node = pq.top().second;
        pq.pop();
        if (!vis[node]) 
		{
            vis[node] = true;
            for (int i = 0; i < graf[node].size(); ++i) 
			{
                int next = graf[node][i].first;
                int cost = graf[node][i].second;
                if (dist[next] > dist[node] + cost) 
				{
                    dist[next] = dist[node] + cost;
                    pq.push({-dist[next], next});
                }
            }
        }
    }
}
 
int main() 
{
    f >> n >> m;
    for (int i = 0; i < m; i++) 
	{
        int x, y, cost;
        fin >> x >> y >> cost;
        graf[x].push_back({y, cost});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) 
	{
        if (dist[i] != 1e9) 
		{
            g << dist[i] << " ";
        }
        else 
		{
            g << 0 << " ";
        }
    }
    g << "\n";
 
    return 0;
}