题目
题解思路
对已连通的边直接并查集连接起来,然后其他的照搬模板。
AC代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 0x3f3f3f3f ;
struct node
{
int q,z,w;
}mp[10100];
int a[1000];
int ans ;
int tmm = 0;
int n,m;
bool cmp(node A ,node B )
{
return A.w < B.w;
}
int find2(int x)
{
if ( x != a[x] )
{
a[x] = find2(a[x]);
}
return a[x];
}
int u(int x,int y)
{
int fx = find2(x);
int fy = find2(y);
if ( fx != fy )
{
a[fx] = fy;
return 1;
}
return 0;
}
void ku()
{
ans = 0;
for (int i = 1 ;i <= m ; i++ )
{
if (u(mp[i].q,mp[i].z))
{
tmm++;
ans += mp[i].w;
}
if (tmm == n -1 )
break;
}
cout<<ans<<"\n";
}
int main()
{
cin>>n;
m = 0;
tmm = 0;
for (int i = 1 ;i <= n ; i++ )
a[i] = i;
for (int i = 1 ;i <= n ; i++ )
{
for (int k = 1 ;k <= n ; k++ )
{
m++;
int b;
cin>>b;
mp[m].q = i;
mp[m].z = k;
mp[m].w = b;
}
}
int j;
cin>>j;
for (int i = 1 ;i <= j ; i++ )
{
int b,c;
cin>>b>>c;
if(u(b,c))
tmm++;
}
sort(mp+1,mp+1+m,cmp);
ku();
return 0;
}