树上的树解题报告

· · 个人记录

树上的树解题报告

首先题意可以理解为取一个路径的子集,子集内两两互不相交,最大化权值和。

Subtask 1 :

Subtask 2 :

Subtask 3 :

Subtask 4 :

Subtask 5 :

代码:使用的是Tarjan求lca

#include<iostream> 
#include<cstdio>
#include<vector>
using namespace std;
#define LL long long
const int Maxx=1000005;
const int Mxdt=100000;
inline char gc(){
    static char buf[Mxdt],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,Mxdt,stdin),p1==p2)?EOF:*p1++;
}
inline int read()
{
    int res=0,bj=0;char ch=gc();
    while(ch<'0'||ch>'9')bj|=(ch=='-'),ch=gc();
    while(ch>='0'&&ch<='9')res=(res<<3)+(res<<1)+(ch^48),ch=gc();
    return bj?-res:res;
}
int n,m,h[Maxx],to[Maxx<<1],nx[Maxx<<1],I[Maxx],O[Maxx],prt[Maxx];
int D[Maxx],Qh[Maxx],Qn[Maxx],Ix[Maxx],Iy[Maxx],wl[Maxx];
LL c[Maxx],F[Maxx];vector<int>vc[Maxx];
inline void ckmax(LL &x,const LL y){x=x>y?x:y;}
inline void ckmax(int &x,const int y){x=x>y?x:y;}
int gf(int x){return prt[x]==x?x:prt[x]=gf(prt[x]);}
inline void Add(int x,const LL v){
    if(v)for(;x<=n;x+=x&-x)c[x]+=v;
}
inline LL Ask(int x){
    static LL res;
    for(res=0,x=I[x];x;x-=x&-x)res+=c[x];
    return res;
}
void Pre(int x,int fa){
    I[x]=++n;
    for(int i=h[x];i;i=nx[i])
    if(to[i]^fa)Pre(to[i],x);
    O[x]=n;
}
void Solve(int x,int fa){
    LL Sum=0,fx=0;
    for(int i=h[x],y;i;i=nx[i])
    if((y=to[i])^fa)Solve(y,x),prt[y]=x,Sum+=F[y];
    for(int i=Qh[x];i;i=Qn[i])vc[gf(Iy[i])].push_back(i);
    if(Sum){
        Add(I[x],Sum);
        for(int i=h[x],y;i;i=nx[i])
        if((y=to[i])^fa)Add(I[y],fx-F[y]),fx=F[y];
        Add(O[x]+1,fx-Sum);
    }
    for(int i=vc[x].size()-1,p;~i;--i)
        p=vc[x][i],ckmax(fx,Ask(Ix[p])+Ask(Iy[p])+wl[p]-Sum);
    ckmax(F[x]=fx,Sum+D[x]);
}
int main()
{
//  freopen("data.in","r",stdin);
//  freopen("data.ans","w",stdout);
    int x,y;
    n=read(),m=read()+1;
    for(int i=1;i<=n;++i)prt[i]=i;
    while(--n){
        nx[n<<1]=h[x=read()],to[h[x]=n<<1]=y=read();
        nx[n<<1|1]=h[y],to[h[y]=n<<1|1]=x;
    }Pre(1,0);
    while(--m){
        if(I[x=read()]<I[y=read()])swap(x,y);
        wl[m]=read(),Ix[m]=x;
        if(x^y)Qn[m]=Qh[x],Iy[Qh[x]=m]=y;
        else ckmax(D[x],wl[m]);
    }Solve(1,0),cout<<F[1]<<"\n";
    return 0;
}

由于出题人太naive,此题被验题人使用树剖+卡常艹过去了,姑且算作另一种解法?