bzoj 1232 [Usaco2008Nov]安慰奶牛cheer
思路:看出跟dfs的顺序有关就很好写了, 对于一棵树来说确定了起点那么访问点的顺序就是dfs序,每个点经过
其度数遍,每条边经过2边, 那么我们将边的权值×2加上两端点的权值跑最小生成树,最后加上一个最小的点的
权值最为dfs的起点。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define pii pair<int,int> #define piii pair<int, pair<int,int> > using namespace std; const int N = 1e4 + 10; const int M = 1e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-6; struct Edge { int u, v, cost; bool operator < (const Edge &rhs) const { return cost < rhs.cost; } }edge[M]; int n, m, c[N], fa[N]; int getRoot(int x) { return x == fa[x] ? x : getRoot(fa[x]); } LL kruscal() { sort(edge + 1, edge + 1 + m); for(int i = 1; i <= n; i++) fa[i] = i; LL ans = 0, cnt = 0; for(int i = 1; i <= m; i++) { int u = edge[i].u, v = edge[i].v, cost = edge[i].cost; int x = getRoot(u), y = getRoot(v); if(x != y) { cnt++; ans += cost; fa[x] = y; if(cnt == n - 1) break; } } return ans; } int main() { scanf("%d%d", &n, &m); int mn = inf; for(int i = 1; i <= n; i++) { scanf("%d", &c[i]); mn = min(mn, c[i]); } for(int i = 1; i <= m; i++) { int u, v, cost; scanf("%d%d%d", &u, &v, &cost); edge[i].u = u; edge[i].v = v; edge[i].cost = 2 * cost + c[u] + c[v]; } LL ans = kruscal() + mn; printf("%lld\n", ans); return 0; } /* */