POJ:3371 Connect the Cities(最小生成树)

时间:2022-12-22 21:59:40

AC代码:

/**
/*@author Victor
/* C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=+;
const int MOD=1e9+;
const double PI = acos(-1.0);
const double EXP = 1E-;
const int INF = 0x3f3f3f3f; const int maxn=+;
struct Edge
{
int from,to,dist;
Edge(int f,int t,int d):from(f),to(t),dist(d) {}
bool operator <(const Edge& a)
{
return dist<a.dist;
}
};
vector<Edge>edges;
int pre[maxn],T[maxn];
//并查集
int find(int x)
{
int i=x;
while(pre[i]!=i)
i=pre[i];
int j=x,k;
while(j!=pre[j])
{
k=pre[j];
pre[j]=i;
j=k;
}
return i;
}
void joint(int x,int y)
{
if(find(x)!=find(y))
pre[find(x)]=find(y);
}
int kruskal()
{
int sum=;
sort(edges.begin(),edges.end());
for(int i=; i<edges.size(); i++)
{
int x=find(edges[i].from),y=find(edges[i].to);
if(x!=y)
{
sum+=edges[i].dist;
pre[x]=y;
}
}
return sum;
}
int main()
{
int n,m,k,Case;
scanf("%d",&Case);
while(Case--)
{
scanf("%d%d%d",&n,&m,&k);
for(int i=; i<=n; i++)
pre[i]=i;
edges.clear();
for(int i=; i<m; i++)
{
int f,t,d;
scanf("%d%d%d",&f,&t,&d);
edges.push_back(Edge(f,t,d));
}
for(int i=; i<k; i++)
{
int t;
scanf("%d",&t);
for(int j=; j<t; j++)
scanf("%d",&T[j]);
for(int j=; j<t; j++)
joint(T[],T[j]);
}
int ans=kruskal();
//通过并查集判断是否联通
bool mark=true;
for(int i=; i<=n; i++)
if(find()!=find(i))
{
mark=false;
break;
}
if(mark==true)
printf("%d\n",ans);
else
printf("-1\n");
}
return ;
}

最小生成树模板

/*
Kruskal 基本模板*/
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3;
struct Edge{
int from,to,dist;
Edge(int f,int t,int d):from(f),to(t),dist(d){}
bool operator <(const Edge& a){
return dist<a.dist;
}
};
vector<Edge>edges;
int pre[maxn];
int find(int x){
int i=x;
while(pre[i]!=i)i=pre[i];
int j=x,k;
while(j!=pre[j]){
k=pre[j];
pre[j]=i;
j=k;
}
return i;
}
void joint(int x,int y){
if(find(x)!=find(y))pre[find(x)]=find(y);
}
int kruskal(){
int sum=;
sort(edges.begin(),edges.end());
for(int i=;i<edges.size();i++){
int x=find(edges[i].from),y=find(edges[i].to);
if(x!=y){
sum+=edges[i].dist;
pre[x]=y;
}
}
return sum;
}
int main(){
int v,e;
while(~scanf("%d%d",&v,&e)){
for(int i=;i<=v;i++)pre[i]=i;
edges.clear();
for(int i=;i<e;i++){
int f,t,d;
scanf("%d%d%d",&f,&t,&d);
edges.push_back(Edge(f,t,d));
}
int ans=kruskal();
printf("%d\n",ans);
}
return ;
}