线段树合并5pts样例不过求调
查看原帖
线段树合并5pts样例不过求调
999274
CNS_5t0_0r2楼主2024/7/13 11:17
#include<bits/stdc++.h>
#define mid ((l + r) >> 1)
#define lchild t[root].Lchild
#define rchild t[root].Rchild
#define lchild2 t[root2].Lchild
#define rchild2 t[root2].Rchild
using namespace std;
const int N = 1e5 + 9;
int n,m;
struct edge{
	int to,nex;
} e[N << 1];
int head[N],ecnt;
void addedge(int u,int v){
	ecnt++;
	e[ecnt] = (edge){v,head[u]};
	head[u] = ecnt;
}

int dep[N],w_ch[N],siz[N];//深度、重儿子、子树大小 
int fa[N];//父亲 
void dfs1(int u,int father){
	siz[u] = 1;
	fa[u] = father;
	for(int i = head[u];i;i = e[i].nex){
		int v = e[i].to;
		if(v == fa[u])
			continue;
		dfs1(v,u);
		if(siz[v] > siz[w_ch[u]])
			w_ch[u] = v;
	}
}
int w_top[N];//重链链头 
void dfs2(int u,int top){
	w_top[u] = top;
	if(w_ch[u]){
		dfs2(w_ch[u],top);
		for(int i = head[u];i;i = e[i].nex){
			int v = e[i].to;
			if(v == fa[u] || v == w_ch[u])
				continue;
			dfs2(v,v);
		}
	}
}

int LCA(int u,int v){
	while(w_top[u] != w_top[v]){
		if(dep[u] < dep[v])
			swap(u,v);
		u = fa[w_top[u]];
	}
	return u;
}

struct node{
	int Max,id;
	int Lchild,Rchild;
} t[N << 6];
int Root[N],node_cnt;
void push_up(int root){
	if(t[lchild].Max > t[rchild].Max){
		t[root].Max = t[lchild].Max;
		t[root].id = t[lchild].id;
	}
	else{
		t[root].Max = t[rchild].Max;
		t[root].id = t[rchild].id;
	}
}
void update(int &root,int l,int r,int v,int k){
	if(!root)
		root = ++node_cnt;
	if(l == r){
		t[root].Max += k;
		t[root].id = l;
		return;
	}
	if(v <= mid)
		update(lchild,l,mid,v,k);
	else
		update(rchild,mid + 1,r,v,k);
	push_up(root);
}
int merge(int root,int root2,int l,int r){
	if(!root || !root2)
		return root | root2;
	if(l == r){
		t[root].Max += t[root2].Max;
		t[root].id = l;
		return root;
	}
	lchild = merge(lchild,lchild2,l,mid);
	rchild = merge(rchild,rchild2,mid + 1,r);
	push_up(root);
	return root;
}
int ans[N];
void dfs3(int u){
	for(int i = head[u];i;i = e[i].nex){
		int v = e[i].to;
		if(v == fa[u])
			continue;
		dfs3(v);
		merge(Root[u],Root[v],1,1e5);
	}
	//cout << u << "在线段树上的根节点是" << Root[u] << '\n'; 
	ans[u] = t[Root[u]].id;
}
int main(){
	ios::sync_with_stdio(false);
	//cin.tie(0);cout.tie(0);
	cin >> n >> m;
	for(int i = 1;i < n;i++){
		int u,v;
		cin >> u >> v;
		addedge(u,v);
		addedge(v,u);
	}
	dfs1(1,0);
	dfs2(1,1);
	for(int i = 1;i <= m;i++){
		int u,v,type;
		cin >> u >> v >> type;
		int lca = LCA(u,v);
		//cout << u << ',' << v << "的LCA是" << lca << '\n';
		//cout << lca << "的父节点是" << fa[lca] << '\n';
		update(Root[u],1,1e5,type,1);
		update(Root[v],1,1e5,type,1);
		update(Root[lca],1,1e5,type,-1);
		update(Root[fa[lca]],1,1e5,type,-1);
	}
	dfs3(1);
	for(int i = 1;i <= n;i++)
		cout << t[Root[i]].id << '\n';
	return 0;
}
2024/7/13 11:17
加载中...