I - Misha and Changing Handles
阿新 • • 發佈:2018-11-01
I - Misha and Changing Handles
題目連結: Misha and Changing Handles
題目概述:輸入n行。每行包括兩個string。設第一個為使用者的oldName,第二個為使用者的newName,用newName 替換舊的oldName,可進行重複替換。最後輸出使用者的第一個Name 和最新的Name。
舉例:
Input:
“`
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output:
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
解題思路:利用 Map 結構。特殊的小技巧是用 newName 作為 key,oldName 作為 value。每次輸入會有兩種情況,一是 Map 中不存在該使用者,直接 `names[newName] = oldName`插入該使用者;二是 Map 已存在該使用者,此時讀取到的 oldName 即為上一次輸入的newName,因此先` names[newName] = names[oldName]`插入新的資訊,在`names.erase(oldName)` 刪除舊資訊
---
最終程式碼:
``` c++
<div class="se-preview-section-delimiter"></div>
#include <iostream>
<div class="se-preview-section-delimiter"></div>
#include <map>
<div class="se-preview-section-delimiter"></div>
#include <string>
using namespace std;
int main()
{
map<string ,string> names;
int q=0;
string oldName,newName;
while(cin>>q){
for(int i = 0; i < q; i++)
{
cin>> oldName>>newName;
if(names.count(oldName)==0){
names[newName] = oldName;
}else{
names[newName] = names[oldName];
names.erase(oldName);
}
}
cout << names.size() <<endl;
for(map<string,string>::iterator it=names.begin(); it != names.end(); it++)
{
cout<< it->second << ' '<< it->first << endl;
}
names.clear();
}
}