Bombs of HRBUST | ||||||
| ||||||
Description | ||||||
Terrorists have placed bombs in each building of HRBUST during Summer Holiday. | ||||||
Input | ||||||
There are multiple test cases. The first line of input is an integer T indicating the number of test cases. Then T test cases follow. | ||||||
Output | ||||||
For each test case: | ||||||
Sample Input | ||||||
2 | ||||||
Sample Output | ||||||
1 | ||||||
Hint | ||||||
For Sample 1: They need to connect bomb 1 and bomb 2, the distance between them are 1m, so the terrorists need 1 minute. | ||||||
Author |
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[103][103];
int pre[1003];
struct data
{
int x,y;
int c;
}num[19993];
int find(int x)
{
if(x!=pre[x])
{
return pre[x]=find(pre[x]);
}
return x;
}
int cmp(data a,data b)
{
return a.c<b.c;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
pre[i]=i;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d",&a[i][j]);
}
}
int m=0;
for(int i=1; i<=n; i++)
{
for(int j=1; j<i; j++)
{
num[m].x=i;
num[m].y=j;
num[m].c=a[i][j];
m++;
}
}
sort(num,num+m,cmp);
int cou=1;
int res=0;
for(int i=0;i<m;i++)
{
if(find(num[i].x)!=find(num[i].y))
{
cou++;
// printf("%d\n",res);
res+=a[num[i].x][num[i].y];
pre[find(num[i].x)]=find(num[i].y);
}
if(cou==n)
{
break;
}
}
printf("%d\n",res);
}
}