The Unique MST ——最小生成树的唯一性

May 26, 2013
Graph

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=24534#problem/C 题目大意:   判断最小生成树是否唯一。 题目思路:   对于如果有一条边A在最小生成树里面,并且存在和这条边权值一样的另外一条边B,那么再次求最小生成树的时候,把A去掉,看看求出的最小生成树是不是和原来的最小生成树权值一样。如果一样,就是不唯一,否则就刚才去掉的加进来,然后再找下一条这样的边。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 110
#define MAXM 5009
typedef struct edge {
  int u, v, w, used, del, equal;
  bool operator < (const edge &other) const {
    return w < other.w;
  }
}edge;
edge edges[MAXM];
int parent[MAXN];
bool first;
int n, m, i, j;
void init() {
  for (i = 1; i <= n; ++i) parent[i] = -1;
}
int find(int x) {
  int s;
  for (s = x; parent[s] >= 0; s = parent[s]) ;
  while (s != x) {
    int tmp = parent[x];
    parent[x] = s;
    x = tmp;
  }
  return s;
}
void Union(int R1, int R2) {
  int r1 = find(R1), r2 = find(R2), tmp = parent[r1] + parent[r2];
  if (parent[r1] > parent[r2]) {
    parent[r1] = r2; parent[r2] = tmp;
  } else {
    parent[r2] = r1; parent[r1] = tmp;
  }
}
int kruscal() {
  int sum = 0, num = 0, u, v;
  init();
  for (i = 1; i <= m; ++i) {
    if (edges[i].del == 1) continue;
    u = edges[i].u; v = edges[i].v;
    if (find(u) != find(v)) {
      sum += edges[i].w; num++;
      Union(u, v);
      if (first) edges[i].used = 1;
    }
    if (num >= n-1) break;
  }
  return sum;
}
int ma[MAXN][MAXN];
int main(void) {
#ifndef ONLINE_JUDGE
  freopen("hust_c.in", "r", stdin);
#endif
  int t; scanf("%d", &t);
  while (t--){
    int u, v, w;
    scanf("%d%d", &n, &m);
    for (i = 1; i<= m; ++i) {
      scanf("%d%d%d", &u, &v, &w);
      edges[i].u = u; edges[i].v = v; edges[i].w = w;
      edges[i].del = 0; edges[i].used = 0; edges[i].equal = 0;
    }
    for (i = 1; i <= m; ++i) {
      for (j = 1; j <= m; ++j) {
        if (i == j) continue;
        if (edges[i].w == edges[j].w) edges[i].equal = 1;
      }
    }
    sort(edges, edges+m);
    first = true;
    int w1 = kruscal(), w2;
    for (i = 1; i<=m; ++i) {
      if (edges[i].used && edges[i].equal) {
        edges[i].del = 1;
        w2 = kruscal();
        if (w1 == w2) {
          printf("Not Unique!\n"); break;
        }
        edges[i].del = 0;
      }
    }
    if (i > m) printf("%d\n", w1);
  }

  return 0;
}

这题以前做过,模板题……

comments powered by Disqus