Title:
There are n princes and m princesses, each with two marriage candidates and dowry.
Now it's time to choose a marriage plan to maximize the dowry for the princes.
Explanation:
It is a legal plan to connect the two candidates of each princess, so that the admission of each Prince is no more than 1.
It can be found that in the end, it is either a base ring tree or a tree. Then we can use the same idea of the maximum spanning tree algorithm to get the maximum dowry.
Code:
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <queue> #include <bitset> #include <map> #include <vector> #include <stack> #include <set> #include <cmath> #ifdef LOCAL #define debug(x) cout<<#x<<" = "<<(x)<<endl; #else #define debug(x) 1; #endif #define chmax(x,y) x=max(x,y) #define chmin(x,y) x=min(x,y) #define lson id<<1,l,mid #define rson id<<1|1,mid+1,r #define lowbit(x) x&-x #define mp make_pair #define pb push_back using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, int> pii; const ll MOD = 1e9 + 7; const double eps = 1e-10; const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3fll; const int MAXN = 1e6 + 5; struct Edge { int u, v, w; bool operator < (const Edge & x) const { return w > x.w; } } e[MAXN]; int par[MAXN]; int Find(int x) { return x == par[x] ? x : par[x] = Find(par[x]); } int had[MAXN]; int main() { #ifdef LOCAL freopen ("input.txt", "r", stdin); #endif int n, m; scanf("%d %d", &n, &m); for(int i = 1; i <= m; i++) { scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w); } for(int i = 1; i <= n; i++) par[i] = i; sort(e + 1, e + 1 + m); int ans = 0; for(int i = 1; i <= m; i++) { int xx = Find(e[i].u), yy = Find(e[i].v); debug(xx) debug(yy) if(xx == yy && !had[xx]) { ans += e[i].w; had[xx] = 1; } else if(xx != yy) { if(had[xx] && had[yy]) continue; par[xx] = yy; had[yy] |= had[xx]; ans += e[i].w; } } printf("%d\n", ans); return 0; }