Uva1395 slim span (minimum spanning tree application)

Title: uva1395 slim span (minimum spanning tree application)
date: 2019-06-04 15:21:55
categories: ACM
tags: [ACM, algorithm]

Title Description

I'll give you an undirected graph. What's the minimum value of T in the spanning tree of this graph?
T: in the spanning tree, the edge with the largest weight - the edge with the smallest weight
My personal blog: https://www.kimiye.xyz

Solving problems

Obviously, it has to do with the minimum spanning tree.
Kruskal algorithm considering minimum spanning tree:
Find the n-1 edge with the least weight that does not form a loop, and add the weight.
Obviously, T value is n-1-1

And then it's not hard to come up with such a conclusion.
Select an edge with the lowest weight as a part of the minimum spanning tree, and the spanning tree with the lowest T value is the minimum spanning tree with the edge as the starting point (minimum value).

So just enumerate the starting point and find the spanning tree with the lowest T value.
The starting range is 1~m-n+2 (at least m-1 edges shall be ensured)

Code:

#include <bits/stdc++.h>
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
const int maxn = 100+7;
const int inf = 0x3f3f3f3f;
struct edge
{
    int u,v,w;
    bool operator < (const edge &a) const
    {
        return w<a.w;
    }
}e[10007];
int n,m,fa[10007];
int getfa(int x)
{
    if(x==fa[x]) return x;
    return fa[x]=getfa(fa[x]);
}
int main()
{
    while(scanf("%d %d",&n,&m)!=EOF && n+m)
    {
        for(int i=1;i<=m;i++)
            scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
        sort(e+1,e+1+m);
        int ans=inf;
        for(int i=1;i<=m-n+2;i++)
        {
            for(int j=1;j<=n;j++) fa[j]=j;
            int cnt=0;
            for(int j=i;j<=m;j++)
            {
                int fx=getfa(e[j].u);
                int fy=getfa(e[j].v);
                if(fx!=fy)
                {
                    fa[fx]=fy;
                    cnt++;
                    if(cnt==n-1)
                    {
                        ans=min(ans,e[j].w-e[i].w);
                        break;
                    }
                }
            }
        }
        if(ans==inf)
            printf("-1\n");
        else printf("%d\n",ans);
    }
    return 0;
}

Posted by digitalecartoons on Thu, 31 Oct 2019 15:56:28 -0700