跳到正文

个人记录

字符串并查集

Haki_bee约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟

版本

  1. v1当前

题目 p2256

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
map<string,string> fa;
string find(string x)
{
	if(fa[x]==x)return x;
	return fa[x]=find(fa[x]);
}
void unionn(string x,string y)
{
	x=find(x),y=find(y);
	if(x!=y)fa[x]=y;
	return ;
}
signed main()
{
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		string s;
		cin>>s;
		fa[s]=s;
	}
	for(int i=1;i<=m;i++)
	{
		string a,b;
		cin>>a>>b;
		unionn(a,b);
	}
	int k;
	cin>>k;
	while(k--)
	{
		string s,t;
		cin>>s>>t;
		if(find(s)==find(t))cout<<"Yes.\n";
		else cout<<"No.\n";
	}
	return 0;
}
原文