2817_树论_最小生成树

lzusa 发布于 2017-11-07 1 次阅读


题目描述

思路

枚举一个最小值用最小生成树求出最小的最大值然后判断即可

 

#include 
#include 
#include 
#include 
using namespace std;
#define fill(x, y) memset(x, y, sizeof(x))
#define N 4001
struct edge
{
    int x, y, w;
}e[N];
int f[N];
int find(int x)
{
    if (!f[x]) return x;
    f[x] = find(f[x]);
    return f[x];
}
int cmp(edge a, edge b)
{
    return a.w < b.w;
}
int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        fill(f, 0);
        int n, m;
        scanf("%d%d", &n, &m);
        int ans = 0x7f7f7f7f;
        for (int i = 1; i <= m; i++)
            scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].w);
        if (m < n - 1)
        {
            printf("-1\n");
            continue;
        }
        sort(e + 1, e + m + 1, cmp);
        for (int i = 1; i <= m; i++)
        {
            fill(f, 0);
            int tot = 0;
            int s = e[i].w;
            for (int j = i; j <= m; j++)
            {
                if (find(e[j].x) != find(e[j].y))
                {
                    tot++;
                    f[find(e[j].x)] = find(e[j].y);
                }
                if (tot == n - 1)
                {
                    int t = e[j].w - s;
                    if (t < ans) ans = t;
                    break;
                }
                if (e[j].w - s > ans) break; 
            }
        }
        if (ans == 0x7f7f7f7f) ans = -1;
        printf("%d\n", ans);
    }
}

 

]]>