HTML & JS
////------start_template-------////
#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define pb push_back
#define ff first
#define ss second

using namespace std;

const ll mod = 1e9 + 7;
const ll mx = 1e17 + 7;
const ll inf = 1e17 + 7;
const ld eps = 0.0000000001;
const char nl = '\n';

void fastio() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
}

// check -> min, max input
// check -> overflow, out of bounds and fastio

////-------end_template--------////

vector< vector<ll> > g(200005);
vector<bool> vis(200005);
string color;
bool flag = 1;

void bfs(ll node) {

	queue<ll> q;
	q.push(node);

	vis[node] = 1;

	ll cnt = 0;
	
	while(!q.empty()) {
		
		ll cur = q.front();
		q.pop();
		
		if(color[cur] == 'B') cnt++;
		
		for(ll i = 0; i < g[cur].size(); i++) {
			if(!vis[g[cur][i]]) {
				q.push(g[cur][i]);
				vis[g[cur][i]] = 1;
			} 
		}
	}
	
	if(cnt > 1) flag = 0;
}


int main() {

	fastio();



	ll t, n;
	cin >> t;
	while(t--) {

		cin >> n;
		for(ll i = 0; i < n+5; i++) 
			vis[i] = 0, g[i].clear();

		cin >> color;

		for(ll i = 0; i < n-1; i++) {
			ll x, y;
			cin >> x >> y;
			x--;
			y--;
			
			if(color[x] == 'G' and color[y] == 'R') continue;
			if(color[x] == 'R' and color[y] == 'G') continue;
			
			g[x].pb(y);
			g[y].pb(x);
		}

		for(ll i = 0; i < n; i++) {
			if(!vis[i]) bfs(i);
		}

		if(flag) cout << "YES\n";
		else cout << "NO\n";
	}

	return 0;
}

Generated URL:

Output:

YES
YES
YES
NO
NO
Report Bug