//Place your snippets for cpp here. Each snippet is defined under a snippet name and has a prefix, body and 
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
// same ids are connected.
// prefix 的格式要求是 acm-[一级标题编号].[二级标题编号][该代码片段的英文简称]
// description 的格式要求是 "插入 [该代码片段的中文名]"

{
    "换根dp": {
        "prefix": "acm-4.5Great Cow Gathering",
        "body": [
            "#include<algorithm>",
            "#include<cstring>",
            "#include<cstdio>",
            "#define LL long long",
            "#define Re register int",
            "using namespace std;",
            "const LL N=1e5+3,inf=1e18;",
            "int n,m,x,y,z,o,A[N],S[N],dis[N],size[N],head[N];LL ans=inf,f[N],g[N];",
            "struct QAQ{int w,to,next;}a[N<<1];",
            "inline void add(Re x,Re y,Re z){a[++o].w=z,a[o].to=y,a[o].next=head[x],head[x]=o;}",
            "inline void in(Re &x){",
            "    int f=0;x=0;char c=getchar();",
            "    while(c<'0'||c>'9')f|=c=='-',c=getchar();",
            "    while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^48),c=getchar();",
            "    x=f?-x:x;",
            "}",
            "inline void dfs1(Re x,Re fa){",
            "\tsize[x]=1,S[x]=A[x];",
            "\tfor(Re i=head[x],to;i;i=a[i].next)if((to=a[i].to)!=fa)",
            "\t\tdis[to]=a[i].w,dfs1(to,x),S[x]+=S[to],size[x]+=size[to],f[x]+=f[to]+(LL)S[to]*a[i].w;",
            "}",
            "inline void dfs2(Re x,Re fa){",
            "\tif(fa)g[x]=g[fa]+f[fa]-f[x]-(LL)S[x]*dis[x]+(LL)(S[1]-S[x])*dis[x];",
            "\tfor(Re i=head[x],to;i;i=a[i].next)if((to=a[i].to)!=fa)dfs2(to,x);",
            "\tans=min(ans,f[x]+g[x]);",
            "}",
            "int main(){",
            "//\tfreopen(\"123.txt\",\"r\",stdin);",
            "\tin(n),m=n-1;",
            "\tfor(Re i=1;i<=n;++i)in(A[i]);",
            "\twhile(m--)in(x),in(y),in(z),add(x,y,z),add(y,x,z);",
            "\tdfs1(1,0),dfs2(1,0),printf(\"%lld\\n\",ans);",
            "}",
            ""
        ],
        "description": "插入 换根dp"
    }
}