AT2673 Tree and Hamilton Pat

https://www.luogu.org/problemnew/show/AT2673

题意:

 

思路:与CF468D TREE类似

 

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define ma(a,b) (a<b?b:a)
#define mi(a,b) (a<b?a:b)
using namespace std;
inline int read(){
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9'){
        x=(x<<3)+(x<<1)+ch-48;
        ch=getchar();
    }
    return x;
}
const int maxn=1e5+4;
int head[maxn],siz[maxn],num[maxn];
long long dep[maxn],ans1=0;
int n,m,cnt=0,rt=0,sum=0x3f3f3f3f,minn=0x3f3f3f3f;
struct node{
    int to,next;
    long long w;
}e[maxn<<1];
inline void add(int u,int v,int w){
    e[cnt].to=v;e[cnt].next=head[u];e[cnt].w=w;head[u]=cnt++;
}
inline void findrt(int u,int fa){
    siz[u]=1;
    for(int i=head[u];i!=-1;i=e[i].next){
        int v=e[i].to;
        if(v==fa) continue;
        findrt(v,u);
        siz[u]+=siz[v];
        num[u]=ma(num[u],siz[v]);
    }
    num[u]=ma(num[u],n-siz[u]);
    if(num[u]<sum){sum=num[u];rt=u;}
}
inline void dfs(int u,int fa){
    ans1+=dep[u];
    for(int i=head[u];i!=-1;i=e[i].next){
        int v=e[i].to;
        if(v==fa) continue;
        dep[v]=(long long)e[i].w+dep[u];
        dfs(v,u);
    }
}
int main(){
    n=read();
    memset(head,-1,sizeof(head));
    for(int i=1;i<=n-1;i++){
        int u=read(),v=read(),w=read();
        add(u,v,w);add(v,u,w);
    }
    findrt(1,0);
    dfs(rt,0);
    ans1<<=1;
    for(int i=head[rt];i!=-1;i=e[i].next){
        int v=e[i].to;
        minn=mi(minn,e[i].w);
        if(num[v]==num[rt]){ans1=(long long)ans1-e[i].w;cout<<ans1;return 0;}
    }
    cout<<(long long)ans1-minn;
}

 

posted @ 2019-01-06 11:22  WiFiMonster  阅读(150)  评论(0编辑  收藏  举报