0
点赞
收藏
分享

微信扫一扫

走廊泼水节「并查集 + 贪心」||「最小生成树」

SPEIKE 2022-03-17 阅读 75

走廊泼水节

题目描述:

思路:

//Work by: Chelsea
#include <bits/stdc++.h>
using namespace std;

#define endl '\n'
#define inf 0x3f3f3f3f
#define mod 1000000007
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d %d",&n,&m)
#define m_p(a,b) make_pair(a, b)
#define mem(a,b) memset((a),(b),sizeof(a))
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)

typedef long long ll;
typedef pair <int,int> pii;

#define MAX 300000 + 50
int n, m, k, op;
struct ran{
    int x, y, z;
    bool operator < (const ran &a)const{
        return z < a.z;
    }
}tr[MAX];
int fa[MAX];
int cnt[MAX];
inline int getfa(int x){
    return fa[x] == x ? x : fa[x] = getfa(fa[x]);
}

void work(){
    cin >> n;
    for(int i = 1; i <= n; ++i){
        fa[i] = i;
        cnt[i] = 1;
    }
    for(int i = 1; i < n; ++i){
        cin >> tr[i].x >> tr[i].y >> tr[i].z;
    }
    sort(tr + 1, tr + n);
    ll ans = 0;
    for(int i = 1; i < n; ++i){
        int xx = getfa(tr[i].x);
        int yy = getfa(tr[i].y);
        ans += (cnt[xx] * cnt[yy] - 1) * (tr[i].z + 1);
        fa[xx] = yy;
        cnt[yy] += cnt[xx];
    }
    cout << ans << endl;
}


int main(){
    io;
    int tt;cin>>tt;
    for(int _t = 1; _t <= tt; ++_t){
        work();
    }
    return 0;
}

举报

相关推荐

0 条评论