【学习笔记】虚树

未完成,先扔几个代码。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int tpos[N],head[N],tot=0,d[N];
struct Edge{int u,v,next;}G[N<<1];
inline void addedge(int u,int v){
    if(u==v)return;
    G[++tot].u=u;G[tot].v=v;G[tot].next=head[u];head[u]=tot;
}
namespace T{

int head[N],cnt=0,tot=0,size[N],fa[N],top[N],wson[N];
struct Edge{int u,v,next;}G[N<<1];
inline void addedge(int u,int v){
    G[++tot].u=u;G[tot].v=v;G[tot].next=head[u];head[u]=tot;
    G[++tot].u=v;G[tot].v=u;G[tot].next=head[v];head[v]=tot;
}
inline void dfs1(int u,int f){
    size[u]=1;
    for(int i=head[u];i;i=G[i].next){
        int v=G[i].v;if(v==f)continue;
        d[v]=d[u]+1;fa[v]=u;
        dfs1(v,u);
        size[u]+=size[v];
        if(size[v]>size[wson[u]])wson[u]=v;
    }
}
inline void dfs2(int u,int tp){
    tpos[u]=++cnt;top[u]=tp;
    if(wson[u])dfs2(wson[u],tp);
    for(int i=head[u];i;i=G[i].next){
        int v=G[i].v;if(v==fa[u]||v==wson[u])continue;
        dfs2(v,v);
    }
}
inline int qlca(int u,int v){
    while(top[u]!=top[v]){
        if(d[top[u]]<d[top[v]])swap(u,v);
        u=fa[top[u]];
    }
    if(d[u]>d[v])swap(u,v);return u;
}

}
inline bool cmp(int x,int y){return tpos[x]<tpos[y];}
int st[N],top=0,vis[N],a[N];
inline void build(){
    int k=read();for(int i=1;i<=k;i++)a[i]=read();
    sort(a+1,a+k+1,cmp);st[++top]=1;
    for(int i=1;i<=k;i++){
        int v=a[i],f=T::qlca(v,st[top]);
        if(f==st[top]){st[++top]=v;continue;}
        while(f==T::qlca(v,st[top-1])){
            addedge(st[top-1],st[top]);top--;f=T::qlca(v,st[top]);
        }
        addedge(f,st[top]);st[top]=f;st[++top]=v;
    }
    while(--top)addedge(st[top],st[top+1]);
}

 

posted @ 2017-09-01 11:29  zcysky  阅读(518)  评论(0编辑  收藏  举报