并查集。。

题目链接

我的另外的解
LCA倍增思想

其实只要并查集维护成森林每个树都是单色的,同色有边就连在一个连通集里面,查询时,如果两个点在同一个树,而且树颜色符合查询的颜色,或者两个点不在同一个树上,必定是经过了查询的颜色的

/*********************************************************************
    程序名:
    版权: Joecai
    作者: Joecai
    日期: 2022-05-04 21:00
    说明:
*********************************************************************/
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
# define rep(i,be,en) for(int i=be;i<=en;i++)
# define pre(i,be,en) for(int i=be;i>=en;i--)
#define ll long long
#define endl "\n"
#define LOCAL
#define pb push_back
#define int	long long
typedef pair<ll, ll> PII;
#define eb emplace_back
#define sp(i) setprecision(i)
const int N = 2e5 + 10, INF = 0x3f3f3f3f;

int fa[N];
int rank[N];
char s[N];
int n, m;
int col[N];
int find(int x)
{
	if (fa[x] == x) return x;
	return fa[x] = find(find(fa[x]));
}


void solve()
{
	cin >> n >> m;
	cin >> s + 1;
	for (int i = 1; i <= n; i++)
	{
		fa[i] = i;
		if (s[i] == 'H') col[i] = 1;
	}
	for (int i = 1; i < n; i++)
	{
		int x, y;
		cin >> x >> y;
		if (col[x] == col[y])
		{
			x = find(x);
			y = find(y);
			fa[x] = y;
		}
	}

	for (int i = 1; i <= m; i++)
	{
		int x, y;
		char t;
		int f = 0;
		cin >> x >> y >> t;
		if (t == 'H') f = 1;
		if (find(x) == find(y) && col[x] == f || find(x) != find(y))
		{
			cout << 1;
		} else cout << 0;
	}
	cout << endl;

}




signed main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//#ifdef LOCAL
	//freopen("data.in.txt","r",stdin);
	//freopen("data.out.txt","w",stdout);
	//#endif
	int __ = 1;
	//cin>>__;
	while (__--)
	{
		solve();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值