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

Posted dwvictor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ:3371 Connect the Cities(最小生成树)相关的知识,希望对你有一定的参考价值。

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=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;

const int maxn=500+10;
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=0;
    sort(edges.begin(),edges.end());
    for(int i=0; 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=1; i<=n; i++)
            pre[i]=i;
        edges.clear();
        for(int i=0; i<m; i++)
        {
            int f,t,d;
            scanf("%d%d%d",&f,&t,&d);
            edges.push_back(Edge(f,t,d));
        }
        for(int i=0; i<k; i++)
        {
            int t;
            scanf("%d",&t);
            for(int j=0; j<t; j++)
                scanf("%d",&T[j]);
            for(int j=1; j<t; j++)
                joint(T[0],T[j]);
        }
        int ans=kruskal();
        //通过并查集判断是否联通
        bool mark=true;
        for(int i=2; i<=n; i++)
            if(find(1)!=find(i))
            {
                mark=false;
                break;
            }
        if(mark==true)
            printf("%d
",ans);
        else
            printf("-1
");
    }
    return 0;
}

 

以上是关于POJ:3371 Connect the Cities(最小生成树)的主要内容,如果未能解决你的问题,请参考以下文章

The search request was unable to connect to the Search Service

How to do if the GM MDI cant connect with the software

hdu 3371 Connect the Cities

解决Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future:(

HDU 3371 Connect the Cities(prim算法)

hdoj-3371-Connect the Cities最小生成树