CF501B Misha and Changing Handles solution
CF501B Misha and Changing Handles
思路
通过并差集,将旧名字的父亲设为新名字。将每个没出现过的旧名字加入初始名字。最后查找旧名字的祖先,就是新名字。
if(!id[old_name]){
id[old_name] = ++ num;
ans[++ cnt] = old_num;//初始名字
}
if(!id[new_name]){
id[new_name] = ++ num;
}
f[old_name] = new_name;
Code
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
using namespace std;
#define db double
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define For(i,j,k) for(int i=j;i<=k;++i)
#define endl '\n'
#define IOS ios::sync_with_stdio(0)
const int M = 2e5 + 10;
int q;
int cnt, num;
string name[M];
map<string, int> id;
map<string, string> f;//用map做father数组
string find(string x){
if(x == f[x]) return x;
return f[x] = find(f[x]);
}
signed main() {
IOS;
cin >> q;
while(q --){
string od, nw;
cin >> od >> nw;
if(id[od] == 0){
id[od] = ++ num;
f[od] = od;
name[++ cnt] = od;
}
if(!id[nw]){
id[nw] = ++ num;
f[nw] = nw;
}
f[od] = nw;
}
cout << cnt << endl;
For(i, 1, cnt){
cout << name[i] << ' ' << find(name[i]) << endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】