并查集求调 qwq
查看原帖
并查集求调 qwq
717286
__HHX__楼主2023/9/3 19:33

十分暴力的解法,尝试不加入第 ii 条边,看其是否联通。

顺便说一下这里好像没有 -1 的数据,而且我的 ans-1 刚好能过所有 WA 的点(AC 的 WA 了)。

#include <iostream>

using namespace std;

const int MaxN = 1e3 + 3, MaxE = 2e3 + 3;

struct Edge { int u, v; } w[MaxE];

int fa[MaxN];

int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); }

int main() {
  int n, m, ans = 0, u, v;
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    cin >> w[i].u >> w[i].v;
  }
  cin >> u >> v;
  for (int i = 0; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
      fa[j] = j;
    }
    for (int j = 1; j <= m; j++) {
      if (j != i) fa[Find(w[j].u)] = Find(w[j].v);
    }
    ans += (Find(u) != Find(v));
  }
  cout << (ans == m + 1 ? -1 : ans);
  return 0;
}
2023/9/3 19:33
加载中...