Pagini recente » Cod sursa (job #1381515) | Cod sursa (job #2657780) | Cod sursa (job #3139533) | Cod sursa (job #3176688) | Cod sursa (job #743925)
Cod sursa(job #743925)
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
const int N = 50005, M = 250005, inf = 0x3f3f3f3f;
int dist[N], n;
bool use[N];
struct Nod
{
int x, cost;
Nod()
{
}
Nod(int _x, int _cost)
{
x = _x;
cost = _cost;
}
inline bool operator< (Nod N)
{
return cost < N.cost;
}
};
struct Heap
{
Nod v[M];
int size;
Heap()
{
size = 0;
}
inline int best(int a, int b)
{
return (b > size || v[a] < v[b]) ? a : b;
}
inline void sch(Nod& a, Nod& b)
{
Nod aux = a;
a = b;
b = aux;
}
void up(int x)
{
while (x > 1 && v[x] < v[x >> 1])
{
sch(v[x], v[x >> 1]);
x >>= 1;
}
}
void down(int x)
{
int m;
while (x <= size)
{
m = best(x << 1, (x << 1) + 1);
if (v[m] < v[x])
return;
sch(v[x], v[m]);
x = m;
}
}
void push(int x)
{
v[++size] = Nod(x, dist[x]);
up(size);
}
int top()
{
return v[1].x;
}
void pop()
{
v[1] = v[ size-- ];
down(1);
}
inline bool empty()
{
return !size;
}
};
vector<Nod> graph[N];
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
void dijkstra(int x)
{
int y, upt;
Heap H;
memset(dist, inf, sizeof(dist));
memset(use, false, sizeof(use));
dist[x] = 0;
H.push(x);
while (!H.empty())
{
x = H.top(); H.pop();
if (use[x])
continue;
use[x] = true;
for (vector<Nod> :: iterator it = graph[x].begin() ; it != graph[x].end() ; it++)
{
y = (*it).x;
upt = dist[x] + (*it).cost;
if (upt < dist[y])
{
dist[y] = upt;
H.push(y);
}
}
}
}
int main()
{
int m, x, y, c;
in >> n >> m;
while (m--)
{
in >> x >> y >> c;
graph[x].push_back(Nod(y, c));
graph[y].push_back(Nod(x, c));
}
dijkstra(1);
for (int i = 2 ; i <= n ; i++)
out << (dist[i] != inf ? dist[i] : 0) << " ";
out << "\n";
return 0;
}