Description
You are given a graph with N nodes and M edges.
Then every time you are required to add an additional edge with 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
题意为,有n个地点,m条边,q个询问。每一次询问后输出一个最小生成树。先算出m条边的最小生成树(否则会超时),然后每加一条边就在原来的最小生成树的基础上在算一次最小生成树。
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int re[1005];
struct edge
{
int s,t,c;
}w[100005];
bool cmp(edge a,edge b)
{
return a.c<b.c;
}
int _find(int x)
{
if(re[x]==x) return x;
else return re[x]=_find(re[x]);
}
int main()
{
int n,m,q;
while(scanf("%d%d%d",&n,&m,&q)!=EOF)
{
int sum=0,cnt=0;
for(int i=1;i<=n;i++)
{
re[i]=i;
}
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&w[i].s,&w[i].t,&w[i].c);
}
sort(w,w+m,cmp);
for(int i=0;i<m;i++)
{
int x=_find(w[i].s);
int y=_find(w[i].t);
if(x!=y)
{
re[x]=y;
sum+=w[i].c;
w[cnt].s=w[i].s;
w[cnt].t=w[i].t;
w[cnt].c=w[i].c;
cnt++;
}
}
for(int i=0;i<q;i++)
{
scanf("%d%d%d",&w[n-1].s,&w[n-1].t,&w[n-1].c);
for(int j=1;j<=n;j++)
{
re[j]=j;
}
sort(w,w+n,cmp);
sum=0;
cnt=0;
for(int j=0;j<n;j++)
{
int x=_find(w[j].s);
int y=_find(w[j].t);
if(x!=y)
{
re[x]=y;
sum+=w[j].c;
w[cnt].s=w[j].s;
w[cnt].t=w[j].t;
w[cnt].c=w[j].c;
cnt++;
}
}
printf("%d\n",sum);
}
}
return 0;
}