【基于map的并查集】
题目中给出的结点是离散的,因此不能用数组
需要用map<int,int>来映射
#include<iostream> #include<map> using namespace std; map<int,int> parent; int getRoot(int i){ if(parent.find(i)==parent.end()) parent[i] = i; while(parent[i]!=i){ i = parent[i]; } return i; } void unionTree(int a,int b){ int root_a = getRoot(a); int root_b = getRoot(b); parent[root_a] = root_b; } int main(){ int a,b; while(cin>>a>>b){ unionTree(a,b); } int counter = 0; map<int,int>::iterator it = parent.begin(); while(it!=parent.end()){ if(it->second==it->first) counter++; it++; } cout<<counter<<endl; return 0; }