[NOIP2017模拟]road

来源:互联网 发布:小明看看白白永久域名 编辑:程序博客网 时间:2024/06/15 21:31

题目背景
SOURCE:NOIP2015-SHY-8

题目描述
给出一张n个点,m条边的无向图,摧毁每条边都需要一定的体力,并且花费的体力值各不相同,给定图中两个点x,y(x≠y),每当(x,y)之间存在路径,就需要不断摧毁当前图中花费体力最少的一条边,直到该路径不联通。他定义cost(x,y)为摧毁(x,y)之间路径花费的体力和。

他想要求出以下这个结果:
这里写图片描述

其中 i,j∈n,并且i<j 。

输入格式
第一行两个整数 n,m ,表示点数和边数。
接下来 m 行,每行三个整数 x,y,z,表示 x 和 y 之间存在一条花费体力为 z 的无向边。

输出格式
输出一个整数表示所求结果。

样例数据
输入
6 7
1 2 10
2 3 2
4 3 5
6 3 15
3 5 4
4 5 3
2 6 6
输出
256

备注
【数据范围】
对 50% 的输入数据 :1≤n≤100;1≤m≤1000
对 100% 的输入数据 :1≤n,m≤100000;1≤z≤100000

分析:考虑并查集,将边从大到小排序,然后一条一条加入边,计算每条边的贡献(使多少点联通了)即可。详细解释见代码。

代码

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<ctime>#include<cmath>#include<algorithm>#include<cctype>#include<iomanip>#include<queue>#include<set>using namespace std;int getint(){    int sum=0,f=1;    char ch;    for(ch=getchar();(ch<'0'||ch>'9')&&ch!='-';ch=getchar());    if(ch=='-')    {        f=-1;        ch=getchar();    }    for(;ch>='0'&&ch<='9';ch=getchar())        sum=(sum<<3)+(sum<<1)+ch-48;    return sum*f;}const int mo=1e+9;long long n,m,cnt,ans,fa[100010],num[100010];struct node{    int fro,to,w;}bian[100010];bool comp(const node &a,const node &b){    return a.w>b.w;}int getfa(int x){    if(x==fa[x])        return x;    fa[x]=getfa(fa[x]);    return fa[x];}int main(){    freopen("road.in","r",stdin);    freopen("road.out","w",stdout);    n=getint();m=getint();    for(int i=1;i<=n;++i)        num[i]=1;    for(int i=1;i<=m;++i)        bian[i].fro=getint(),bian[i].to=getint(),bian[i].w=getint();    sort(bian+1,bian+m+1,comp);    for(int i=1;i<=n;++i)        fa[i]=i;    for(int i=1;i<=m;++i)    {        int x=getfa(bian[i].fro),y=getfa(bian[i].to);        if(x!=y)//如果这两个祖先不同(即这是两个联通快)        {            fa[x]=y;//合并            cnt+=num[x]*num[y];//这条边的连接使两个联通快的每一个点都两两联通了,也就是说当“摧毁”了这条边后就可以让这两个联通快的点都断开,所以这条边要被“摧毁”cnt+num[x]*num[y]次(cnt是比它大的边需要被摧毁的总次数,所以它被迫多摧毁cnt次)            num[y]=num[x]+num[y];//把两个联通快的点数合并        }        ans=(ans+bian[i].w*cnt%mo)%mo;//ans加上它的贡献(记得取模)    }    cout<<ans<<'\n';    return 0;}

本题结。

原创粉丝点击