码迷,mamicode.com
首页 > 其他好文 > 详细

poj slim span

时间:2015-03-12 11:33:09      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:acm   poj   

#include <bits/stdc++.h>

using namespace std;
#define N 105
#define INF 0x7ffffff
struct Edge
{
    int u;
    int v;
    int w;
}edge[N*N/2];

int n, m, span, p[N], rank[N];

int cmp(Edge a, Edge b)
{
    return a.w<b.w;
}

int find(int x)
{
    return p[x] == x ? x : p[x] = find(p[x]);
}

void unionSet(int x, int y)
{
    if (rank[x] > rank[y]) p[y] = x;
    else {
        p[x] = y;
        if (rank[x] == rank[y]) rank[y]++;
    }
}

void kruskal()
{
    sort(edge+1, edge+m+1, cmp);

    for(int i=1; i<=m-n+2; i++)
      {
          int cnt = 0;
          int start = 0;
          for(int j=1; j<=n; j++) p[j] = j;
          memset(rank, 0, sizeof(rank));
          for(int k=i; k<=m; k++)
          {
              int x = find(edge[k].u);
              int y = find(edge[k].v);
              if(x != y)
              {
                  unionSet(x,y);
                  cnt++;
                  if(!start)
                   start = i;
                  if(cnt == n-1)
                  {
                      span = min(span, edge[k].w-edge[start].w);
                      break;
                  }
              }
          }
      }
      if(span == INF) cout<<-1<<endl;
      else cout<<span<<endl;
}

int main()
{
      while(~scanf("%d%d",&n, &m) && n+m)
    {
        for(int i=1; i<=m; i++)
        cin>>edge[i].u>>edge[i].v>>edge[i].w;
        span = INF;
        kruskal();
    }
    return 0;
}

poj slim span

标签:acm   poj   

原文地址:http://blog.csdn.net/dojintian/article/details/44218781

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!