题目大意:就是讲在codeforces网站上,由于一个黑客,大家都可以随便改名字了,有的人就改了一次又一次,(当然也有的人就只改一次)然后题目问你一共有多少个人改了名字,输出人的数量并且输出他们的最初名字和最终名字。
题目思路:
既然前后改的都是名字,也就是字符串,可以考虑map,map里面也是pair,几乎完全符合题目要求哎;由于最后只要输出最初的名字和最后的名字,可以考虑以每一次的新名字作为关键字,把旧名字当成键值,之后如果这个人又改了名字,也就是说新名字变成了旧名字,可以直接在map中查找,找到了就把新的新名字作为关键字,此时的键值改成原来那个新名字的键值,也就是之前的旧名字;
总的来说就是:名字1--->名字2;名字2--->名字3;map[名字2]=名字1,mp[名字3]=mp[名字2]
题目链接:戳我戳我
AC代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<map>
using namespace std;
map<string,string>mp;
int main(void)
{
int n;
string str1,str2;
scanf("%d",&n);
while(n--)
{
cin>>str1>>str2;
if(mp.find(str1)==mp.end())
{
mp[str2]=str1;
}
else
{
mp[str2]=mp[str1];
mp.erase(str1);//记得把之前的给撤销掉
}
}
int num=mp.size();
printf("%d\n",num);
map<string,string>::iterator it;
for(it=mp.begin();it!=mp.end();it++)
{
cout<<it->second<<" "<<it->first<<endl;
}
return 0;
}
呼呼