題意:給n個城市,m條路,k組已知路,求最小費用聯通所有城市;
思路:先連已知的,在連沒連的;
坑點,兩處,已標記在代碼中
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
struct node
{
int x,y,value;
}city[100050];
int root[550];
int times,n,m,k;
bool cmp(node a,node b)
{
return a.value<b.value;
}
int find_root(int son)
{
if(son!=root[son])
{
root[son]=find_root(root[son]);
}
return root[son];
}
int main()
{
scanf("%d",×);
while(times--)
{
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n;i++)
{
root[i]=i;
}
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&city[i].x,&city[i].y,&city[i].value);
}
sort(city+1,city+m+1,cmp);
int fx,fy;int sum=0;int flag=0;
for(int i=1;i<=k;i++)
{
int j;int l;int p;
scanf("%d",&j);scanf("%d",&l);
for(int kk=2;kk<=j;kk++)
{
scanf("%d",&p);
fx=find_root(l);//此處如果不判斷的話會爆棧,
fy=find_root(p);
if(fx!=fy)
{
root[fy]=fx;
}
}
}
for(int i=1;i<=m;i++)
{
fx=find_root(city[i].x);
fy=find_root(city[i].y);
if(fx!=fy)
{
root[fy]=fx;
sum+=city[i].value;
}
}
for(int i=1;i<=n;i++)//如果用數組記錄根節點有多少子節點會超時
{
if(root[i]==i)
{
flag++;
}
}
if(flag==1) printf("%d\n",sum);
else printf("-1\n");
}
return 0;
}