题意:用二维数组的方式告诉你两个点(两个城市)的距离(费用或者权值),然后告诉你n个城市中有q个是连通的,求修完剩下的路中最少需要多少钱。
思路:用结构体存储城市间的权值(费用),按权值小到大sort一遍,然后用连——找——连的思路解题。
一连:把q个城市组连在一起。
找:在结构体中找到没有连入的点,只要没有连成一棵树,就找。
二连:在找到需要修路的城市时,连接并加上权值即可。
有思路的话,用通用的模板就可以A掉了,还是那句话,有思路就要自己写试试。
总结:逻辑要强,我写了四遍,wa了n遍,终于找到合适的方法了,并且毫无保留的奉献出来,看见其他同学很顺利的一遍A,感觉自己脑力还是没锻炼出来啊,加油吧!
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int x,y,value;
}city[102*102];//结构体存所有城市间的权值
int n,q;int root[102];int num[102];
bool cmp(node a,node b)
{
return a.value<b.value;
}//sort升序,按权值
int find_root(int son)
{
if(son!=root[son])
{
root[son]=find_root(root[son]);
}
return root[son];
}//找根,不用多说
int main()
{
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
int k=1;
for(int i=1;i<=n;i++)//输入
{
for(int j=1;j<=n;j++)
{
city[k].x=i;
city[k].y=j;
scanf("%d",&city[k].value);
k++;
}
}
sort(city+1,city+n*n+1,cmp);//sort一遍,
// for(int i=1;i<=n*n;i++)
// {
// printf("%d %d %d\n",city[i].x,city[i].y,city[i].value);
// }//方便读者检查
for(int i=1;i<=n;i++)
{
root[i]=i;num[i]=1;
}//初始化数组
int xx, yy,fx,fy;
scanf("%d",&q);
while(q--)//一连,解释在上面
{
scanf("%d%d",&xx,&yy);
fx=find_root(xx);
fy=find_root(yy);
if(fx!=fy)
{
root[fx]=fy;
num[fy]+=num[fx];
}
}
int money=0;//计算最少钱数
for(int i=1;i<=n*n;i++)
{
fx=find_root(city[i].x);
fy=find_root(city[i].y);//找,解释还是在上面
if(fx!=fy)
{
root[fx]=fy;
num[fy]+=num[fx];
money+=city[i].value;//二连,解释还在上面
}
if(num[fx]>=n||num[fx]>=n) break;//小优化,所有点都连好,就跳出循环
}
printf("%d\n",money);
}
return 0;
}