Mai intai trebuie sa te autentifici.
Cod sursa(job #2678920)
| Utilizator | Data | 29 noiembrie 2020 01:47:37 | |
|---|---|---|---|
| Problema | Algoritmul lui Dijkstra | Scor | 20 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.63 kb |
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int oo = 1 << 30;
bool vizitat[100005];
int n, x, m, y, nodStart, cost[100005], z;
struct compare {
bool operator()(int x, int y)
{
if (cost[x] < cost[y])
return 1;
return 0;
}
};
vector <pair<int,int>> G[100005];
priority_queue <int, vector<int>, compare> Q;
void Dijkstra(int nod)
{
cost[nodStart] = 0;
Q.push(nodStart);
vizitat[nodStart] = true;
while (!Q.empty())
{
int curr = Q.top();
Q.pop();
for (unsigned int i = 0; i < G[curr].size(); i++)
{
int Vecin = G[curr][i].first;
int Cost = G[curr][i].second;
if (cost[curr] + Cost < cost[Vecin])
{
cost[Vecin] = cost[curr] + Cost;
if (!vizitat[Vecin])
{
vizitat[Vecin] = true;
Q.push(Vecin);
}
}
}
}
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> z ;
G[x].push_back(make_pair(y,z));
}
nodStart = 1;
for (int i = 1; i <= n; i++)
{
cost[i] = oo;
}
Dijkstra(nodStart);
for (int i = 2; i <= n; i++)
{
if (cost[i] == oo)
{
fout << 0<< " ";
}
else {
fout << cost[i] << " ";
}
}
return 0;
}