Pagini recente » Cod sursa (job #3149449) | Cod sursa (job #2138712) | Cod sursa (job #41685) | Cod sursa (job #1185279) | Cod sursa (job #1002004)
# include <cstring>
# include <iostream>
# include <fstream>
# include <vector>
# include <set>
using namespace std;
# define INF 0x3f3f3f3f
# define MAXN 50010
typedef vector< pair<int, int> > :: iterator iter;
class heap{
private:
vector< pair<int, int> > a;
# define father(x) (x >> 1)
# define left_son(x) (x << 1)
# define right_son(x) ((x << 1) + 1)
public:
heap() {};
void insert(pair<int, int> x) {
a.push_back(x);
int k = a.size() - 1;
while ((k > 0) && (a[k] < a[father(k)])) {
swap(a[k], a[father(k)]);
k = father(k);
}
}
pair<int, int> top() {
if (a.size() > 0) {
return a[0];
}
return make_pair(0, 0);
}
void pop() {
a[0] = a[a.size() - 1];
a.pop_back();
int k = 0;
while (right_son(k) < a.size() && (a[k] > a[left_son(k)] || a[k] > a[right_son(k)])) {
if (a[left_son(k)] > a[right_son(k)]) {
swap(a[k], a[right_son(k)]);
k = right_son(k);
} else {
swap(a[k] , a[left_son(k)]);
k = left_son(k);
}
}
if (left_son(k) < a.size() && a[k] > a[left_son(k)]) {
swap(a[k] , a[left_son(k)]);
}
}
bool empty() {
return a.empty();
}
int size() {
return a.size();
}
};
// <parsing>
FILE *fin = fopen("dijkstra.in", "r");
const int maxb = 8192;
char buf[maxb];
int ptr = maxb - 1;
int getInt() {
while (buf[ptr] < '0' || '9' < buf[ptr]) {
if (++ptr >= maxb) {
fread(buf, maxb, 1, fin);
ptr = 0;
}
}
int nr = 0;
while ('0' <= buf[ptr] && buf[ptr] <= '9') {
nr = nr * 10 + buf[ptr] - '0';
if (++ptr >= maxb) {
fread(buf, maxb, 1, fin);
ptr = 0;
}
}
return nr;
}
// </parsing>
ofstream g("dijkstra.out");
int n, m;
vector<pair<int, int> > G[MAXN];
int dist[MAXN];
heap coada;
void dijkstra()
{
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
coada.insert(make_pair(0, 1));
while (!coada.empty()) {
pair<int, int> nd = coada.top();
coada.pop();
for (iter it = G[nd.second].begin(); it != G[nd.second].end(); it++) {
if (dist[it->first] > dist[nd.second] + it->second) {
dist[it->first] = dist[nd.second] + it->second;
coada.insert(make_pair(dist[it->first], it->first));
}
}
}
for (int i = 2; i <= n; i++) {
if (dist[i] == INF) {
g << 0 << ' ';
} else {
g << dist[i] << ' ';
}
}
}
int main()
{
n = getInt();
m = getInt();
cout << n << ' ' << m;
for (int i = 1; i <= m; i++) {
int x, y, cost;
x = getInt();
y = getInt();
cost = getInt();
G[x].push_back(make_pair(y, cost));
}
dijkstra();
fclose(fin);
g.close();
return 0;
}