• 长链剖分学习笔记


    长链剖分学习笔记

    长链剖分

    长链剖分可以把维护与深度有关的复杂度做到线性。长链是指把深度最大的儿子作为重儿子,每次继承信息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;
    } 
    
  • 相关阅读:
    python 字符串前面加u,r,b的含义
    文本检测: CTPN
    ocr 识别 github 源码
    python 中写hive 脚本
    Win10 环境安装tesseract-ocr 4.00并配置环境变量
    OCR 识别原理
    pandas set_index和reset_index的用法
    整理 pandas 常用函数
    js es6 map 与 原生对象区别
    js 暂时性死区
  • 原文地址:https://www.cnblogs.com/lcyfrog/p/12758820.html
Copyright © 2020-2023  润新知