题目链接 HDU3371
【题意】给出m(m<=25000)条边,和一些已经连通的点,求最小生成树的值,不存在输出-1;
【分析】用的是kruskal算法,一开始想到直接把已经连通的点的边赋值为费用为0的边,然后再把这些边直接加到给出的边中,然后kruskal,但是这样写不用加速挂很容易超时;
于是在做UVA的时候想到了一个小优化:其实不需要把费用为0的边(就是连通点的边)加到有费用的边中在计算,因为这些边已经选择完了,然后只需要把已经联通了的点用并查集直接加到各自对应的集合,并计算上用来计数的cnt(为了后面判断是否有解,也可以加快kruskal),这样只需要对前面给出的所有边在次基础上用kruskal就好了。
【AC CODE】 328ms
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 510
struct NODE{
int a, b, v;
bool operator < (const NODE& t) const {return v < t.v;}
}p[25010];
int ans,ch,f[MAXN];
int in()//加了输入挂
{
while((ch = getchar()) < '0' || '9' < ch);
ans = ch-'0';
while((ch = getchar()) >= '0' && '9' >= ch) ans = ans*10+ch-'0';
return ans;
}
int find(int x){return f[x] == x ? x : f[x] = find(f[x]);}
int main()
{
#ifdef SHY
freopen("e:\\1.txt","r",stdin);
#endif
int t;
scanf("%d%*c", &t);
while(t--)
{
int n = in(),m = in(),k = in(), cnt = 1;
for(int i = 0; i <= n; i++) f[i] = i;
for(int i = 0; i < m; i++)
p[i].a = in(), p[i].b = in(), p[i].v = in();
sort(p,p+m);
for(int i = 0; i < k; i++)
{
int len = in();
int y = find(in()); //把第一个点所在集合设为下面连通的边合并的集合
for(int j = 1; j < len; j++)//把已经修建完的路(也就是边为0)的城市直接连通,并cnt计数
{
int x = find(in());
if(x != y) f[x] = y, cnt++;
}
}
ans = 0;
for(int i = 0; i < m && cnt < n; i++)
{
int x = find(p[i].a), y = find(p[i].b);
if(x != y) ans += p[i].v, f[x] = y, cnt++;
}
if(cnt < n) puts("-1");
else printf("%d\n", ans);
}
return 0;
}