CodeForces 120F - 简单的树形DP

        题意:

      有N颗树...问合并后能得到的最长路径...

        题解:

                  大水题...练习赛的时候居然没注意到...简单的树形DP...找出每颗树的最长路径...相加就是答案...


Program:

#include<iostream>
#include<stdio.h>
#include<cmath>
#include<string.h>
#include<stack>
#include<queue>
#include<algorithm>
#define oo 1000000007
#define ll long long 
#define MAXN 105
using namespace std;   
vector<int> T[MAXN];
int dp[MAXN],M;
void dfs(int x,int father)
{
       int i,y,m=T[x].size();
       dp[x]=0;
       for (i=0;i<m;i++)
       {
              y=T[x][i];
              if (y==father) continue;
              dfs(y,x);
              M=max(M,dp[x]+dp[y]+1);
              dp[x]=max(dp[x],dp[y]+1);
       }
       return;      
}
int main()
{ 
       int t,ans;
       freopen("input.txt","r",stdin);
       freopen("output.txt","w",stdout); 
       scanf("%d",&t);
       ans=0;
       while (t--)
       {
              int n,i;
              scanf("%d",&n);
              for (i=1;i<=n;i++) T[i].clear();
              for (i=1;i<n;i++)
              {
                     int x,y;
                     scanf("%d%d",&x,&y);
                     T[x].push_back(y);
                     T[y].push_back(x);
              }
              M=0;
              dfs(1,0);
              ans+=M;
       }
       printf("%d\n",ans);
       return 0;
}


你可能感兴趣的:(CodeForces 120F - 简单的树形DP)