标签:oid too bool cos while 生成树 bit space name
最小生成树指的是在图上面找到权值最小的一棵树,并且保证图上所有的点都在这棵树上。
解决办法:Kruskal 算法(贪心思想)
/** * Fuck you. * I love you too. */ #include<bits/stdc++.h> #define lson i<<2 #define rson i<<2|1 #define LS l,mid,lson #define RS mid+1,r,rson #define mem(a,x) memset(a,x,sizeof(a)) #define gcd(a,b) __gcd(a,b) #define ll long long #define ull unsigned long long #define lowbit(x) (x&-x) #define enld endl #define mian main #define itn int #define prinft printf const double PI = acos (-1.0); const int INF = 0x3f3f3f3f; const int EXP = 1e-8; const int N = 1e5 + 5; const int MOD = 1e9 + 7; const int MAXN = 1e5 + 5; using namespace std; int n; int ans; int par[N]; struct ed { int s, e, cost; } edge[MAXN]; bool cmp (ed a, ed b) { return a.cost < b.cost; } int Find (int a) { return a == par[a] ? a : par[a] = Find (par[a]); } void join (int a, int b) { par[Find (a)] = Find (b); } int main() { while (~scanf ("%d", &n)) { ans = 0; for (int i = 0; i < n; ++i) { scanf ("%d%d%d", &edge[i].s, &edge[i].e, &edge[i].cost); par[edge[i].s] = edge[i].s; par[edge[i].e] = edge[i].e; } sort (edge, edge + n, cmp); for (int i = 0; i < n; ++i) { if (Find (edge[i].s) != Find (edge[i].e)) { cout << edge[i].s << ‘ ‘ << edge[i].e << endl; join (edge[i].s, edge[i].e); ans += edge[i].cost; } } cout << ans << endl; } return 0; }
标签:oid too bool cos while 生成树 bit space name
原文地址:https://www.cnblogs.com/chunibyo/p/9409281.html