关于 TLE
查看原帖
关于 TLE
420102
phmaprostrate楼主2021/10/26 07:58

TT 成了 4848 是树刨写错了吗?

#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int n,m;
char a[N];
int hh[N],g[N];
struct node {
	int to,next;
} tr[2 * N];
int h[N],k = 0;
void add(int from,int to) {
	tr[++k].to = to;
	tr[k].next = h[from];
	h[from] = k;
}
int siz[N],dad[N],deep[N],big[N];
int top[N],dfn[N],num;
void dfs1(int now,int fa) {
	hh[now] = hh[fa] + (a[now] == 'H');
	g[now] = g[fa] + (a[now] == 'G');
	dad[now] = fa;
	deep[now] = deep[fa] + 1;
	for(int i = h[now] ; i ; i = tr[i].next) {
		int v = tr[i].to;
		if(v == fa) continue;
		dfs1(v,now);
		if(big[now] == 0 || siz[big[now]] < siz[v]) big[now] = v;
	}

}
void dfs2(int now,int to) {
	dfn[now] = ++num;
	top[now] = to;
	if(big[now]) dfs2(big[now],to);
	for(int i = h[now] ; i ; i = tr[i].next) {
		int v = tr[i].to;
		if(v == dad[now] || v == big[now]) continue;
		dfs2(v,v);
	}
}
int lca(int x,int y) {
	while(top[x] != top[y]) {
		if(deep[top[x]] < deep[top[y]])
			swap(x,y);
		x = dad[top[x]];
	}
	if(deep[x] > deep[y]) swap(x,y);
	return x;
}
bool check(int l,int r,int id) {
	int la = lca(l,r);
	if(id == 1) {
     if(hh[l] + hh[r] - hh[la] - hh[dad[la]]) return true;
     else return false;
	}
	if(id == 2){
		if(g[l] + g[r] - g[la] - g[dad[la]]) return true;
		else return false;
	}
}
int main() {
//	freopen("a.in","r",stdin);
//	freopen("a.out","w",stdout);
	scanf("%d%d",&n,&m);
   cin >> a + 1;
	for(int i = 1 ; i < n ; i ++) {
		int u,v;
		scanf("%d%d",&u,&v);
		add(u,v);
		add(v,u);
	}
	dfs1(1,0);
	dfs2(1,1);
	while(m --) {
		int l,r;
		char ch;
		scanf("%d%d",&l,&r);cin >> ch;
		if(ch == 'H' && check(l,r,1)) printf("1");
		else if(ch == 'G' && check(l,r,2)) printf("1");
		else printf("0");
	}
	return 0;
}
2021/10/26 07:58
加载中...