ACM Misha and Changing Handles

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 andnew 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 handle new 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 and new, 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.

Example

Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

 1 /*
 2     Name: Misha and Changing Handles
 3     Copyright: 
 4     Author: 
 5     Date: 10/08/17 09:34
 6     Description:给定多个改名的查询,每个查询包括一个新名字和旧名字,一个人可以多次更改,
 7                 最终得到一个新名字,求这些查询中一共有多少个人,
 8                 并且输出他最初的名字和最后的名字。(1<=q<=100) 
 9 */
10 #include<iostream>
11 #include<cstring>
12 #include<algorithm>
13 #include<map>
14 using namespace std;
15 
16 int main()
17 {
18     int t;
19     map<string,string>Users;
20     string old,newl;
21     while(cin>>t)
22     {
23         while(t--)
24         {
25             cin>>old>>newl;
26             if(!Users.count(old))   
27             {
28                 Users[old] = old;
29             }
30             Users[newl] = Users[old];
31             Users.erase(old);
32         }        
33         cout<<Users.size()<<endl;
34         map<string,string>:: iterator item;
35         for(item = Users.begin();item != Users.end();item++)
36             cout<<(*item).second<<" "<<(*item).first<<endl;
37     }
38 
39     return 0;
40 }
41 /*
42     把(A,B),(B,C)-->(A,C)
43     使用map,需要在输入后处理和输出处处理 
44     (A,B),(B,C)-->(B,A),(C,B)-->(C,A)-->(A,C) 
45 */ 
View Code

 

posted @ 2017-08-10 11:11  听说这是最长的名字了  阅读(159)  评论(0编辑  收藏  举报