不止代码:保留道路(ybtoj 最小生成树)
生活随笔
收集整理的這篇文章主要介紹了
不止代码:保留道路(ybtoj 最小生成树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目描述
- 解析
- 代碼
- thanks for reading!
題目描述
解析
其實就是修建道路
我一開始只能想到枚舉g去跑最小生成樹
是m^2的算法(50pts)
但是其實每次加入的邊只有一條
而且之前都不在最小生成樹上的邊以后也肯定不會在
所以可以建一個新的邊的集合存當前生成樹的邊
這個集合的邊最多只有n條
這樣復雜度就降為n*m
可以通過本題
代碼
#include <bits/stdc++.h> #define ll long long using namespace std; const int N = 600; const int M = 1e5 + 100; int n, m; ll wwg, wws; struct node {int x, y;ll g, s;bool operator<(const node y) const { return g < y.g; } } p[M], p2[N], now[N]; int tot; int fa[N]; int find(int x) {if (fa[x] == x)return x;return fa[x] = find(fa[x]); } ll ans = 2e18; bool cmp(node x, node y) { return x.s < y.s; } void kruscal(int k) {for (int i = 1; i <= tot; i++) {p2[i] = now[i];}p2[tot + 1] = p[k];sort(p2 + 1, p2 + 1 + tot + 1, cmp);for (int i = 1; i <= n; i++) fa[i] = i;ll num = 0, gmax = 0, smax = 0;for (int i = 1; i <= tot + 1; i++) {int xx = find(p2[i].x), yy = find(p2[i].y);if (xx != yy) {fa[xx] = yy;gmax = max(gmax, p2[i].g);smax = max(smax, p2[i].s);now[++num] = p2[i];}}tot = num;if (num == n - 1) {ans = min(ans, gmax * wwg + smax * wws);} } int main() {scanf("%d%d%lld%lld", &n, &m, &wwg, &wws);for (int i = 1; i <= m; i++) {scanf("%d%d%lld%lld", &p[i].x, &p[i].y, &p[i].g, &p[i].s);}sort(p + 1, p + 1 + m);for (int i = 1; i <= m; i++) {kruscal(i);// printf("i=%d tot=%d\n",i,tot);}if (ans != 2e18)printf("%lld", ans);elseprintf("-1");return 0; } /* 3 3 2 1 1 2 10 15 1 2 4 20 1 3 5 1 */thanks for reading!
總結
以上是生活随笔為你收集整理的不止代码:保留道路(ybtoj 最小生成树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TechInsights:2023 年
- 下一篇: qq公众号:服务号和订阅号、购物号有什么