poj 1848 Tree

//poj 1848 Tree (树型DP)
//很详细的解题报告:http://hi.baidu.com/19930705cxjff/blog/item/1df66e4a4ff3022e08f7ef5d.html

 

#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
const int inf=1<<28;
int n,m,k;
const int vmax = 100;

vector<int> con[vmax+5];
int dp[vmax+5][3];
int p[vmax+5];

void dfs(int v)
{
     for (int i=0;i<con[v].size();i++)
     {
         int j=con[v][i];
         if (p[j]!=-1 ) continue;
         p[j]=v;
         dfs(j);
     }   
}

void solve(int v)
{
    int sum=0;
    for (int i=0;i<con[v].size();i++)
    {
        int j=con[v][i];
        if (j==p[v]) continue;
        leaf=false;
        solve(j);
        sum+=dp[j][0];
    }

    dp[v][1]=sum;
    dp[v][0]=dp[v][2]=inf;
   
    for (int i=0;i<con[v].size();i++)
    {
        int j=con[v][i];
        if (j==p[v]) continue;
        dp[v][2]=min(dp[v][2],sum-dp[j][0]+min(dp[j][1],dp[j][2]));
        for (int l=i+1;l<con[v].size();l++)
        {
            int k=con[v][l];
            if (k==p[v]) continue;
            dp[v][0]=min(dp[v][0],sum-dp[j][0]-dp[k][0]+min(dp[j][1],dp[j][2])+min(dp[k][1],dp[k][2])+1);
        }
        dp[v][0]=min(dp[v][0],sum-dp[j][0]+dp[j][2]+1);
    }
}
int main()
{
    while (scanf("%d",&n)!=EOF)
    {
          for(int i=1;i<=n;i++) con[i].clear();
          int a,b;
          for (int i=1;i<n;i++)
          {
              scanf("%d%d",&a,&b);
              con[a].push_back(b);
              con[b].push_back(a);
          }
          memset(p,-1,sizeof(p));
          p[1]=1;
          dfs(1);

          //memset(dp,0,sizeof(dp));
          solve(1);
          if (dp[1][0]>=inf) printf("-1/n");
          else printf("%d/n",dp[1][0]);
         
         
         
    }
    //system("pause");
    return 0;
}

你可能感兴趣的:(poj 1848 Tree)