首页 > 代码库 > CF 501 B Misha and Changing Handles【map函数】
CF 501 B Misha and Changing Handles【map函数】
Description
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handlenew is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old andnew, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
【题意】好坏好坏,第三者前来插足了!!!!!!!!但是结局就尴尬了。告诫原配,莫要学B出轨,可能自己一无所有。
输入一系列字符串,A B(顺序不可改变), C D, B S,由于出现A B, B S那么就划去B,直接把A S连在一起,第三者S借B成功和A在一起,在一起,当然S也有可能步入B的结果,嘻嘻,看后来有没有勾引S了,接下来以此类推。
【思路】借助map函数(大神博客http://blog.csdn.net/sunshinewave/article/details/8067862)
map<string,string>ma; ma[a]是前面的string, a是后面的string
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<iostream> 5 #include<map> 6 #include<algorithm> 7 using namespace std; 8 int main() 9 { 10 string a,b;11 map<string,string>ma;12 int n;13 scanf("%d",&n);14 for(int i=0;i<n;i++)15 {16 cin>>a>>b; 17 if(!ma.count(a))18 { ma[b]=a; }19 else20 { ma[b] = ma[a]; ma.erase(a); }21 }22 printf("%d\n",ma.size());23 map<string,string>::iterator it;24 for(it=ma.begin();it!=ma.end();it++)//map函数的输出 25 cout<<it->second<<‘ ‘<<it->first<<endl;26 return 0; 27 }
CF 501 B Misha and Changing Handles【map函数】