QTREE3 - Query on a tree again! 树链

Posted xxfy1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QTREE3 - Query on a tree again! 树链相关的知识,希望对你有一定的参考价值。

树链剖分应用题,看到一群大佬各种LCT,Splay,瑟瑟发抖ing


struct edge {
    int u,v,cost;
};
int fa[N],lv[N],siz[N],son[N],top[N],dfn[N],cnt=0;
vector<pii> G[N];
int n,seg[N<<2];
edge e[N];

int query(int s,int t,int l,int r,int p) {
    if(s<=l&&r<=t) return seg[p];
    int m=(l+r)/2;
    if(t<=m) return query(s,t,l,m,p<<1);
    if(m+1<=s) return query(s,t,m+1,r,p<<1|1);
    return min(query(s,t,l,m,p<<1),query(s,t,m+1,r,p<<1|1));
}

void update(int pos,int l,int r,int p){
    if(l==r) {
        if(seg[pos]==INT_MAX) seg[pos]=pos;
        else seg[pos] = INT_MAX;
        return;
    }
    int m=(l+r)/2;
    if(pos<=m) update(pos,val,l,m,p<<1);
    else update(pos,val,m+1,r,p<<1|1);
    seg[p]=min(seg[p<<1],seg[p<<1|1]);
}

int dfs1(int x,int fx) {
    son[x]=-1;
    siz[x]=1;
    fa[x]=fx;
    lv[x]=lv[fx]+1;
    for(auto p:G[x]) {
        int to = p.first;
        if(to==fx) continue;
        siz[x] += dfs1(to,x);
        if(son[x] == -1 || siz[to] > siz[son[x]]) son[x] = to;
    }
    return siz[x];
}

void dfs2(int x,int root) {
    top[x]=root;
    dfn[x]=++cnt;
    if(son[x]==-1) return;
    dfs2(son[x],root);
    for(auto p:G[x]) {
        int to = p.first;
        if(to == son[x] || to == fa[x]) continue;
        dfs2(to,to);
    }
}

int ask(int x,int y) {
    int ans=INT_MAX;
    while(x==y) {
        ans=min(ans, query(dfn[top[y]], dfn[y],1,n,1));
        y=fa[top[y]];
    }
    if(ans == INT_MAX) ans=-1;
    return ans;
}

int a,b,c;
string o;

void solve() {
    memset(seg,0,sizeof(seg));
    cnt = 0;
//    cin>>n;
    scanf("%d %d",&n,&q);
    for(int i=1;i<=n;i++) G[i].clear();
    for(int i=1;i<n;i++){
        scanf("%d %d %d",&a,&b,&c);
        G[a].push_back({b,c});
        G[b].push_back({a,c});
        e[i]={a,b,c};
    }
    dfs1(1,-1);
    dfs2(1,1);
    for(int i=1;i<n;i++){
        if(lv[e[i].u] > lv[e[i].v]) swap(e[i].u, e[i].v);
        update(dfn[e[i].v], e[i].cost, 1,n,1);
    }
    while(q--) {
        scanf("%d %d",&o,&x);
        if(o==0) update(dfn[x],1,n,1);
        else cout<<ask(1,n)<<endl;
    }
}

int main(){
    ios::sync_with_stdio(false);
    int t;
    scanf("%d",&t);
    while(t--) solve();
    return 0;
}

以上是关于QTREE3 - Query on a tree again! 树链的主要内容,如果未能解决你的问题,请参考以下文章

SPOJ QTREE - Query on a tree

bzoj3639: Query on a tree VII

bzoj3637: Query on a tree VI

Query on a tree III

Query on a tree II

[hdu4010]: Query on The Trees