题解 | #第一题# 简便的并查集做法
第一题
https://www.nowcoder.com/practice/7c29cdfa28274c86afc9e88c07448a10
#include <iostream> using namespace std; const int N = 1000100; int p[N]; int e[N]; bool st[N]; int find(int x) { if(x != p[x]) p[x] = find(p[x]); return p[x]; } int main() { for(int i = 0; i < N; i++) p[i] = i; int a, b; int res = 0, j = 0; while(cin >> a >> b) { p[find(a)] = find(b); e[j++] = a; e[j++] = b; } for(int i = 0; e[i] != 0; i++) if(!st[e[i]] && find(e[i]) == e[i]) { st[e[i]] = true; res++; } cout << res << endl; }