The Unique MST-- minimum spanning tree (unique determination of the minimum spanning tree)

Topic Link

Meaning of the questions:

To a map, ask the minimum spanning tree is unique.

answer:

Value is calculated using the Kruskal minimum spanning tree, and record each side, and then enumerate them to look to remove the same whether it can be constructed and the value of the minimum spanning tree.

Note that after the deleted edges may constitute a tree in FIG obtain a judgment.

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 10005;
int f[maxn];
int n,cnt,m;
int vis[maxn];
struct node
{
    int u,v;
    int w;
    bool operator < (const node &a)const
    {
        return w<a.w;
    }
} edge[maxn];

int Find(int x)
{
    return x==f[x]?x:f[x]=Find(f[x]);
}
void add(int u,int v,int w)
{
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt++].w=w;
}

void kruskal()
{
    int ans=0;
    int cntt=0;
    int flag=1;
    for(int i=0; i<=n; i++)f[i]=i;
    sort(edge,edge+cnt);
    for(int i=0; i<cnt; i++)
    {
        int x=edge[i].u;
        int y=edge[i].v;
        int fx=Find(x);
        int fy=Find(y);
        if(fx!=fy)
        {
            f[fx]=fy;
            vis[cntt++]=i;
            ans+=edge[i].w;

        }
    }

    for(int i=0;i<cntt;i++)
    {
        for(int k=0; k<=n; k++)f[k]=k;
        int sum=0,res=0;
        for(int j=0;j<cnt;j++)
        {
            if(j==vis[i])continue;
            int x=edge[j].u;
            int y=edge[j].v;
            int fx=Find(x);
            int FY = the Find (Y); 

            IF (! FX = FY) 
            { 
                F [FX] = FY; 
                RES + = Edge [J] .W; 
                SUM ++ ; 
            } 
        } 
        IF (ANS == == SUM n-RES && - . 1 ) In Flag = { 0 ; BREAK ;} /// determining whether the tree can be constructed and whether or equal to the minimum spanning tree 
    }
     iF (In Flag) the printf ( " % D \ n- " , ANS);
     the else the printf ( " Not of Unique! \ n- " ); 


} 

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        cnt=0;
        for(int i=1; i<=m; i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
        }
        kruskal();

    }


    return 0;
}
kruskal

 

Guess you like

Origin www.cnblogs.com/j666/p/11617275.html