hdu2196 Computer待续

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;
inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
    while(isdigit(ch)){x=10*x+ch-'0';ch=getchar();}
    return x*f;
}
int n,first[10010],to[10010],next[10010],val[10010],cnt;
inline void add(int u,int v,int w)
{
    to[++cnt]=v;
    next[cnt]=first[u];
    first[u]=cnt;
    val[cnt]=w;
}
int dp[10010][2],depth1[10010],depth2[10010];
int dfs1(int x,int fa)
{
    for(int i=first[x];i;i=next[i])
    {
        int v=to[i];
        if(v==fa)continue;
        dp[x][0]=max(dfs(v)+val[i],dp[x][0]);
    }
    return dp[x][0];
}
int vis[10010];
int dfs2(int x,int fav)
{
    int max1=0,max2=0;
    int flag1,flag2;
    if(vis[x])continue;
    for(int i=first[x];i;i=next[i])
    {
        int v=to[i];
        if(vis[v])continue;
        int tmp=dp[v][0]+val[i];
        if(tmp>max1)
        {
            max2=max1;
            max1=tmp;
            flag2=flag1;
            flag1=v;
        }
        if(tmp==max1 || tmp>max2)
        {
            max2=max1;
            max1=tmp;
            flag2=v;
        }
    }
    if(x!=1)
    {
        int tmp=dp[x][1];
        int v=-2;
        if(tmp>max1)
        {
            max2=max1;
            max1=tmp;
            flag2=flag1;
            flag1=v;
        }
        if(tmp==max1 || tmp>max2)
        {
            max2=max1;
            max1=tmp;
            flag2=v;
        }
    }
    for(int i=first[x];i;i=next[i])
    {
        int v=to[i];
        if(v==flag1)
            dp[x][1]=max2+val[i];
        else dp[x][1]=max1+val[i];
        dfs2(v,val[i]);
    }
}
int main()
{
    n=read();
    for(int i=1;i<n;i++)
    {
        int u,v,w;
        u=read();v=read();w=read();
        add(u,v,w);add(v,u,w);
    }
    dfs1(1,-1);
}

 

posted @ 2017-11-09 16:24  探险家Mr.H  阅读(233)  评论(0编辑  收藏  举报