Pagini recente » Cod sursa (job #1400048) | Cod sursa (job #33060) | Cod sursa (job #2602860)
#include <bits/stdc++.h>
using namespace std;
#define N 50005
#define ps push_back
ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");
vector <pair <int, int> > ad[N];
pair <int, int> heap[250006];
int viz[N];
int cost[N];
int oo = N;
int n, m;
void downheap (int l)
{
int i = 1;
while (2 * i <= l)
{
if (2 * i + 1 <= l)
{
if (heap[2 * i + 1].second < heap[2 * i].second && heap[2 * i + 1].second < heap[i].second)
swap (heap[2 * i + 1], heap[i]);
else if (heap[2 * i].second < heap[i].second)
swap (heap[2 * i], heap[i]);
}
else if (heap[i].second > heap[2 * i].second)
swap (heap[i], heap[2 * i]);
i *= 2;
}
}
void upheap (int l)
{
while (l / 2)
{
if (heap[l / 2].second > heap[l].second)
swap (heap[l], heap[l / 2]);
l /= 2;
}
}
void dijkstra ()
{
heap[1] = {1, 0};
int l = 1;
while (l)
{
int front = heap[1].first;
heap[1] = heap[l];
l--;
downheap (l);
if (!viz[front])
{
viz[front] = 1;
for (int i = 0 ; i < ad[front].size (); i++)
{
if (!viz[ad[front][i].first])
{
heap[++l] = {ad[front][i].first, ad[front][i].second};
if (cost[front] + ad[front][i].second < cost[ad[front][i].first])
cost[ad[front][i].first] = cost[front] + ad[front][i].second;
upheap (l);
}
}
}
}
}
int main ()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
fin >> x >> y >> z;
ad[x].ps ({y, z});
ad[y].ps ({x, z});
}
for (int i = 1; i <= n; ++i)
cost[i] = +oo;
cost[1] = 0;
dijkstra ();
for (int i = 2; i <= n; i++)
if (cost[i] == oo)
fout << 0 << " ";
else
fout << cost[i] << " ";
}