In order to prepare the “The First National ACM School Contest” (in 20??) the major of the citydecided to provide all the schools with a reliable source of power. (The major is really afraid ofblackoutsJ). So, in order to do that, power station “Future” and one school (doesn’t matter which one)must be connected; in addition, some schools must be connected as well.
You may assume that a school has a reliable source of power if it’s connected directly to “Future”,or to any other school that has a reliable source of power. You are given the cost of connection betweensome schools. The major has decided to pick out two the cheapest connection plans – the cost of theconnection is equal to the sum of the connections between the schools. Your task is to help the major— find the cost of the two cheapest connection plans.
Input
Output
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<vector>
#include<map>
#include<cstring>
using namespace std;
#define min(a,b) ((a)>(b)?(b):(a))
#define MAX 1000000000
int UFS[108],in[108][108],n,m;
int UFS_find(int x)
{
if(x!=UFS[x])
UFS[x]=UFS_find(UFS[x]);
return UFS[x];
}
void UFS_insert(int x,int y)
{
x=UFS_find(x);
y=UFS_find(y);
UFS[max(x,y)]=min(x,y);
}
struct AP
{
int x,y,value;
bool operator <(const AP &a)const
{
return value>a.value;
}
};
AP func1(int x,int y,int z)
{
AP t;
t.x=x;
t.y=y;
t.value=z;
return t;
}
int main()
{
int N;
cin>>N;
while(N--)
{
priority_queue<AP>que1;
vector<AP>vec1;
queue<AP>que3;
memset(in,0,sizeof(in));
cin>>n>>m;
while(m--)
{
int x1,x2,x3;
cin>>x1>>x2>>x3;
if(x1!=x2)
{
in[x1][x2]=in[x2][x1]=x3;
que1.push(func1(x1,x2,x3));
}
}
for(int i=1; i<=n; i++)
UFS[i]=i;
int T=n-1,sum=0,ans=0;
while(!que1.empty())
{
AP temp;
temp=que1.top();
que1.pop();
if(UFS_find(temp.x)!=UFS_find(temp.y))
{
UFS_insert(temp.x,temp.y);
vec1.push_back(temp);
ans+=temp.value;
sum++;
if(T==sum)
{
while(!que1.empty())
{
que3.push(que1.top());
que1.pop();
}
break;
}
}
else
que3.push(temp);
}
cout<<ans<<' ';
int MIN=MAX;
while(!que3.empty())
{
AP temp=que3.front();
que3.pop();
for(int i=1; i<=n; i++)
UFS[i]=i;
UFS[max(temp.x,temp.y)]=min(temp.y,temp.x);
T=n-2;
sum=0;
ans=temp.value;
vector<AP>::iterator it;
for(it=vec1.begin(); it!=vec1.end(); it++)
if(UFS_find((*it).x)!=UFS_find((*it).y))
{
UFS_insert((*it).x,(*it).y);
ans+=(*it).value;
sum++;
if(T==sum)
break;
}
MIN=min(MIN,ans);
}
cout<<MIN<<endl;
}
return 0;
}