模板:Prime最小生成树堆优化 + Dijkstra单源最短路堆优化
生活随笔
收集整理的這篇文章主要介紹了
模板:Prime最小生成树堆优化 + Dijkstra单源最短路堆优化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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; }總結
以上是生活随笔為你收集整理的模板:Prime最小生成树堆优化 + Dijkstra单源最短路堆优化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj 2528 线段树离散化+染色
- 下一篇: 简单dfs序 + 树链剖分