宿命的PSS

宿命的PSS

思路:

考虑克鲁斯卡尔算法,每次我们选取最小的边,并且这条要连接两个联通块,那么记联通块\(1\)\(x\)个点,联通块\(2\)\(y\)个点,则其他除了当前边其他的\(x*y-1\)条边的大小必定是这条最小边的长度\(+1\)

题链

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef struct node
{
    int x,y,cost;
}tree_node;
tree_node edge[20005];
bool cmp(node a,node b)
{
    return a.cost < b.cost;
}
int bin[20005];
int du[20005];
void min_c(int n);
int find_boot(int id);
int main(void)
{
    int n;
    scanf("%d",&n);
    for(int i = 0;i < 20005;i++)
        du[i] = 1,bin[i] = i;
    for(int i = 0;i < n-1;i++)
        scanf("%d %d %d",&edge[i].x,&edge[i].y,&edge[i].cost);
    sort(edge,edge+n-1,cmp);
    min_c(n);
    return 0;
}
int find_boot(int id)
{
   while(id!=bin[id])
       id = bin[id];
       return id;
}
void min_c(int n)
{
    LL sum = 0;
    for(int i = 0;i < n-1;i++)
    {
        int x_id = find_boot(edge[i].x);
        int y_id = find_boot(edge[i].y);
        sum = sum + (LL)(edge[i].cost + 1LL)*((LL)du[x_id]*(LL)du[y_id] - 1LL);
        sum += edge[i].cost;
        if(du[x_id] > du[y_id])
        {
            du[x_id] += du[y_id];
            bin[y_id] = x_id;
        }
        else
        {
            du[y_id] += du[x_id];
            bin[x_id] = y_id;
        }
    }
    printf("%lld\n",sum);
}

posted @ 2018-05-05 17:25  sCjTyC  阅读(239)  评论(0编辑  收藏  举报