C - Spanning Tree 最小生成树 Kruskal (第四届华中区程序设计邀请赛暨武汉大学第十三届校赛)

来源:互联网 发布:怎样给淘宝客服发图片 编辑:程序博客网 时间:2024/05/16 01:43
点击打开链接
http://acm.whu.edu.cn/land/problem/detail?problem_id=1566&contest_id=14


C - Spanning Tree


Description
You are given a graph with N nodes and M edges. 
Then every time you are required to add an additional edgewith weight Wi connecting the node Ai and Bi in the graph, and then calculate the sum of the edges’ weight of the Minimum Spanning Tree of the current graph. You’ll be asked to complete the mission for Q times.
The Minimum Spanning Tree of a graph is defined to be a set of N - 1 edges which connects all the N nodes of the graph and the sum of all the edges is as small as possible.
It's guaranteed that the graph is connected.
Input
First line of each case contains three numbers N , M and Q.(1 ≤  N,Q ≤ 1000, 1 ≤  M ≤ 100000 ,)
The following M lines contains three numbers Ai , Bi and Wi.( 1 ≤  Ai, Bi ≤ 1000, 1 ≤  Wi≤ 100000).
The last Q lines of this case contains three numbers Ai , Bi and Wi. ( 1 <= Ai, Bi <= 1000, 1 ≤  Wi≤ 100000 ). 

Output
Output the answer in a single line for each case.

Sample Input
3 3 3
2 1 8
3 1 4
1 2 6
1 2 4
2 3 1
1 1 4
3 3 3
2 1 7
3 2 8
3 3 6
1 3 3
2 2 3
2 2 3

Sample Output
8
5
5
10
10
10



/*  给一个图,每次都加一个边,求在每次加边的基础上的最小生成树,(注意是继续加边)  先是第一次Kruskal,形成了n个点n-1个边的树,  每次Q操作加上一个新加的边,就是n个点n个边的图,直接对n的图进行Kruskal  复杂度 m*logm+q*(n*logn)  = n^2*logn*/#include<iostream>#include<cstdio>#include<algorithm>using namespace std;int w[100005],p[1005],r[100005],u[100005],v[100005],w2[1005],u2[1005],v2[1005]; //u,v是边的两个端点,w是边的权值,v2.u2.w2.是辅助转存的数组int cmp(int i,int j) //排序函数{    return w[i]<w[j];}int fin(int x) //并查集的find{    return p[x]==x?x:p[x]=fin(p[x]);}int Kruskal(int n,int m){    int ans=0,q=0;    for(int i=0;i<n+2;i++) p[i]=i;//初始化并查集    for(int i=0;i<m+2;i++) r[i]=i;//初始化边序号    sort(r,r+m,cmp);//给边排序    for(int i=0;i<m;i++)    {        int e=r[i];        int x=fin(u[e]);        int y=fin(v[e]);//找x与y的集合        if(x!=y)//不连通,则连接x.y,并记录        {            ans+=w[e];            p[x]=y;            w2[q]=w[e];u2[q]=u[e];v2[q++]=v[e];//转存,方便下一次Kruskal        }    }    return ans;}int main(){    int n,m,q,i,x,y,z;    while(~scanf("%d%d%d",&n,&m,&q))    {        m++;q--;        for(i=0;i<m;i++)        {            scanf("%d%d%d",&x,&y,&z);            u[i]=x;v[i]=y;w[i]=z;        }        printf("%d\n",Kruskal(n,m));//第一次Kruskal,比较耗时间        while(q--)        {            for(i=0;i<n-1;i++)            {                w[i]=w2[i];u[i]=u2[i];v[i]=v2[i];            }            scanf("%d%d%d",&x,&y,&z);            u[i]=x;v[i]=y;w[i]=z;            printf("%d\n",Kruskal(n,n));//n个点,(n-1)+1 =  n   个边        }    }    return 0;}


0 0
原创粉丝点击