CF 501B Misha and Changing Handles(map+技巧)
题意:A有别名B,B有别名C......求实际上有多少个人,并输出最后一个别名
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
思路:构造MAP。(B,A) .(C,B).就能直接构造出数对(C,A),运用mp[s2] = mp[s1];进行转换
#include <iostream> #include <cstdio> #include <set> #include <map> #include <string> using namespace std; int n; string s1,s2; map<string,string>mp; int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n; for(int i=0;i<n;i++) { cin>>s1>>s2; if(mp.count(s1)==0) mp[s1]=s1; mp[s2]=mp[s1]; mp.erase(s1); } cout<<mp.size()<<endl; for(map<string,string>::iterator it=mp.begin();it!=mp.end();it++) { cout<<(*it).second<<" "<<(*it).first<<endl; } return 0; }