zoukankan      html  css  js  c++  java
  • 长链剖分学习笔记

    长链剖分学习笔记

    长链剖分

    长链剖分可以把维护与深度有关的复杂度做到线性。长链是指把深度最大的儿子作为重儿子,每次继承信息O(1)从重儿子那里继承,其余从轻儿子暴力合并。一条长链指挥合并一次,不难证明线性时间复杂度。

    void dfs(int now,int fa){
    	for(int i=head[now];i;i=edge[i].nex){
    		int v=edge[i].v;
    		if(v==fa) continue;
    		dfs(v,now);
    		if(len[v]>len[son[now]]) son[now]=v;
    	}
    	len[now]=len[son[now]]+1;
    }
    

    例题 CF1009F

    求出对于每个深度在哪个点子树内这个深度的点最多,模板题。

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    #include<cmath>
    using namespace std;
    #define ll long long
    int read(){
    	int x=0;int pos=1;char ch=getchar();
    	for(;!isdigit(ch);ch=getchar()) if(ch=='-') pos=0;
    	for(;isdigit(ch);ch=getchar()) x=(x<<1)+(x<<3)+ch-'0';
    	return pos?x:-x; 
    }
    
    const int N = 1e6+100;
    int n;
    struct node{
    	int v,nex;
    }edge[N*2];
    int head[N];int top=0;
    void add(int u,int v){
    	edge[++top].v=v;
    	edge[top].nex=head[u];
    	head[u]=top;
    }
    int tmp[N],*id=tmp,*f[N],cnt,len[N],son[N],ans[N];
    void dfs(int now,int fa){
    	for(int i=head[now];i;i=edge[i].nex){
    		int v=edge[i].v;
    		if(v==fa) continue;
    		dfs(v,now);
    		if(len[v]>len[son[now]]) son[now]=v;
    	}
    	len[now]=len[son[now]]+1;
    }
    void dp(int u,int fa){
    	f[u][0]=1;
    	if(son[u]) f[son[u]]=f[u]+1,dp(son[u],u),ans[u]=ans[son[u]]+1;
    	for(int i=head[u];i;i=edge[i].nex){
    		int v=edge[i].v;
    		if(v==fa||v==son[u]) continue;
    		f[v]=id;id+=len[v];dp(v,u);
    		for(int j=1;j<=len[v];j++){
    			f[u][j]+=f[v][j-1];
    			if((j<ans[u]&&f[u][j]>=f[u][ans[u]])||(j>ans[u]&&f[u][j]>f[u][ans[u]])) ans[u]=j;
    		}
    	}
    	if(f[u][ans[u]]==1) ans[u]=0;
    }
    int main(){
    	n=read();
    	for(int i=1;i<n;i++){
    		int u=read(),v=read();
    		add(u,v);add(v,u); 
    	}
    	dfs(1,0);f[1]=id;id+=len[1];
    	dp(1,0);
    	for(int i=1;i<=n;i++){
    		printf("%d
    ",ans[i]);
    	}
    	return 0;
    } 
    
  • 相关阅读:
    LeetCode 189. Rotate Array
    LeetCode 965. Univalued Binary Tree
    LeetCode 111. Minimum Depth of Binary Tree
    LeetCode 104. Maximum Depth of Binary Tree
    Windows下MySQL的安装与配置
    LeetCode 58. Length of Last Word
    LeetCode 41. First Missing Positive
    LeetCode 283. Move Zeroes
    《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》读后感
    删除docker下的镜像
  • 原文地址:https://www.cnblogs.com/lcyfrog/p/12758820.html
Copyright © 2011-2022 走看看