题解 | #第一题#
第一题
http://www.nowcoder.com/practice/7c29cdfa28274c86afc9e88c07448a10
并查集简单运用
#include<iostream>
#include<map>
using namespace std;
map<int,int> mp;
int find(int x){
if(x != mp[x])
return mp[x] = find(mp[x]);
return mp[x];
}
int main()
{
int a,b,cnt = 0;
while(cin >> a >> b && a && b){
if(mp.find(a) == mp.end())
mp[a] = a;
if(mp.find(b) == mp.end())
mp[b] = b;
int c1 = find(a);
int c2 = find(b);
if(c1 == c2)continue;
else
mp[c1] = c2;
}
for(auto it : mp)
if(it.first == it.second)
cnt++;
cout << cnt;
}