Dijkstra 单源最短路堆优化
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
int head[N], to[N], value[N], nex[N], cnt = 1;
int n, m, rt, st, dis[N], visit[N];
struct cmp {
bool operator()(PII a, PII b) {
return a.second > b.second;
}
};
void add(int x, int y, int w) {
to[cnt] = y;
nex[cnt] = head[x];
value[cnt] = w;
head[x] = cnt++;
}
void Dijkstra() {
memset(dis, 0x3f, sizeof dis);
dis[rt] = 0;
priority_queue<PII, vector<PII>, cmp> q;
q.push(make_pair(rt, 0));
while(!q.empty()) {
int p = q.top().first;
q.pop();
if(visit[p]) continue;
visit[p] = 1;
for(int i = head[p]; i; i = nex[i]) {
if(dis[to[i]] > dis[p] + value[i]) {
dis[to[i]] = dis[p] + value[i];
q.push(make_pair(to[i], dis[p] + value[i]));
}
}
}
for(int i = 1; i <= n; i++)
printf("%d%c", dis[i] == 0x3f3f3f3f ? (int)((1ll << 31) - 1) : dis[i], i == n ? '\n' : ' ');
}
int main() {
int x, y, w;
scanf("%d %d %d", &n, &m, &rt);
for(int i = 0; i < m; i++) {
scanf("%d %d %d", &x, &y, &w);
add(x, y, w);
}
Dijkstra();
return 0;
}
Prime 最小生成树堆优化
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int N1 = 5e3 + 10, N2 = 4e5 + 10;
int head[N1], nex[N2], to[N2], value[N2], cnt = 1;
int visit[N1], dis[N1], n, m, ans;
struct cmp {
bool operator () (const PII & a, const PII & b) const {
return a.second > b.second;
}
};
void add(int x, int y, int w) {
to[cnt] = y;
value[cnt] = w;
nex[cnt] = head[x];
head[x] = cnt++;
}
void prime() {
int flag = 0;
for(int i = 1; i <= n; i++) dis[i] = INF;
dis[1] = 0;
priority_queue<PII, vector<PII>, cmp> q;
q.push(make_pair(1, 0));
while(!q.empty()) {
int temp = q.top().first;
int add = q.top().second;
q.pop();
if(visit[temp]) continue;
visit[temp] = 1;
flag++;
ans += add;
for(int i = head[temp]; i; i = nex[i]) {
if(dis[to[i]] > value[i]) {
dis[to[i]] = value[i];
q.push(make_pair(to[i], value[i]));
}
}
}
if(flag == n) printf("%d\n", ans);
else puts("orz");
}
int main() {
// freopen("in.txt", "r", stdin);
int x, y, w;
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++) {
scanf("%d %d %d", &x, &y, &w);
add(x, y, w);
add(y, x, w);
}
prime();
return 0;
}