CF196E Opening Portals
生活随笔
收集整理的這篇文章主要介紹了
CF196E Opening Portals
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
CF196E Opening Portals
給定一個有nnn個節點,mmm條邊的無向聯通圖,有kkk個點有portalsportalsportals,當經過了某個點,如果這個點有portalportalportal,它就會永久開啟,
對于任意兩個開啟的portalportalportal,我們可以不需要花時間穿行,問開啟所有的portalportalportal需要多少時間。
可以考慮這是一個1?>Sv1->S_v1?>Sv?,SvS_vSv?是另kkk個portalsportalsportals聯通的最小生成樹,
因此我們的答案就是1?>nearest∈k1->nearest\in k1?>nearest∈k,再加上最小生成樹的代價,
我們另這kkk個點去跑最短路,然后把原本的邊{u,v,w}\{u, v, w\}{u,v,w}變為{nearest∈kofu,nearest∈kofv,dis[u]+dis[v]+w}\{nearest \in k\ of\ u, nearest \in k\ of\ v, dis[u] + dis[v] + w\}{nearest∈k?of?u,nearest∈k?of?v,dis[u]+dis[v]+w}
kkk點中與uuu最近的點,kkk點中與vvv最近的點,邊權同時更新,最后只需要跑一個最小生成樹計算代價即可。
#include <bits/stdc++.h>using namespace std;const int N = 1e5 + 10;struct Res {int u, v;long long w;void read() {scanf("%d %d %lld", &u, &v, &w);}bool operator < (const Res &t) const {return w < t.w;} }edge[N];struct Node {int u; long long w;bool operator < (const Node &t) const {return w > t.w;} };int n, m, k, vis[N], fa[N], pre[N];long long dis[N];vector< pair<int, int> > G[N];int find(int rt) {return rt == fa[rt] ? rt : fa[rt] = find(fa[rt]); }int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);scanf("%d %d", &n, &m);for (int i = 1; i <= m; i++) {edge[i].read();G[edge[i].u].push_back({edge[i].v, edge[i].w});G[edge[i].v].push_back({edge[i].u, edge[i].w});}scanf("%d", &k);priority_queue<Node> q;memset(dis, 0x3f, sizeof dis);for (int i = 1, x; i <= k; i++) {scanf("%d", &x);q.push({x, 0});pre[x] = x;dis[x] = 0;}while (q.size()) {auto u = q.top().u;q.pop();if (vis[u]) {continue;}vis[u] = 1;for (auto &to : G[u]) {if (dis[to.first] > dis[u] + to.second) {dis[to.first] = dis[u] + to.second;pre[to.first] = pre[u];q.push({to.first, dis[to.first]});}}}long long ans = dis[1];for (int i = 1; i <= m; i++) {edge[i].w += dis[edge[i].u] + dis[edge[i].v];edge[i].u = pre[edge[i].u], edge[i].v = pre[edge[i].v];}sort(edge + 1, edge + 1 + m);for (int i = 1; i <= n; i++) {fa[i] = i;}for (int i = 1, cur = 1; i <= m && cur < n; i++) {int u = find(edge[i].u), v = find(edge[i].v);if (u ^ v) {cur++;fa[u] = v;ans += edge[i].w;}}printf("%lld\n", ans);return 0; }總結
以上是生活随笔為你收集整理的CF196E Opening Portals的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 老陈醋泡黑豆的功效与作用、禁忌和食用方法
- 下一篇: 绿豆莲藕汤的功效与作用、禁忌和食用方法