B. Misha and Changing Handles

B. Misha and Changing Handles
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 handle newis 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.

Examples
input
Copy
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
output
Copy
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

 题意:输入n行,每行两个单词代表旧昵称和新昵称,问一共有几个用户更改昵称,输出这些用户的初始昵称和最终昵称

题解:map匹配:把新昵称最为键值,如果旧昵称匹配过,更新匹配

 

#include
#include
#include<string.h>
#include<string>
#include
#include
#include<set>
#define ll long long
using namespace std;
map<string,string>m;
string s,ss;
int n;
int main()
{
    cin>>n;
    while(n--)
    {
        cin>>s>>ss;//s旧名字,ss新名字
        if(m.count(s)==0)
            m[ss]=s;
        else
        {
           m[ss]=m[s];
            m.erase(s);
        }
    }
    cout<endl;
        map<string,string>::iterator it;
        for(it=m.begin();it!=m.end();it++)
            cout<second<<' '<first<<endl;

    return 0;

}

 

转载于:https://www.cnblogs.com/-citywall123/p/11240867.html

你可能感兴趣的:(数据结构与算法)