并查集

#include<iostream>
#include<cstdio>
using namespace std;
#define MAXN 100005
int p[MAXN],N;
int Find(int x) {return x == p[x] ? x : p[x] = Find(p[x]);}
int main()
{
    //freopen("sample.txt","r",stdin);
    int u, v;
    while (scanf("%d",&u) != EOF)
    {
        int ans = 0;
        if (u == -1) break;
        for (int i = 0; i < MAXN; i++) p[i] = i;
        scanf("%d",&v);
        int x = Find(u), y = Find(v);
        if (x != y) p[x] = y;
        else ans++;
        while (scanf("%d",&u) != EOF)
        {
            if (u == -1) break;
            scanf("%d",&v);
            int x = Find(u), y = Find(v);
            if (x != y) p[x] = y;
            else ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

相关文章:

  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-12-05
  • 2022-03-04
  • 2021-09-17
  • 2021-10-17
  • 2021-07-22
猜你喜欢
  • 2022-12-23
  • 2021-08-22
  • 2022-12-23
  • 2021-07-21
  • 2021-12-06
  • 2021-08-12
  • 2021-09-23
相关资源
相似解决方案