//枚举所有边,把该树分为两个树,分别求两颗数的最小的改变量
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std ;
const int maxn = 3030 ;
const int inf = 0x7fffffff ;
int dp[maxn] ;
struct Edge
{
int flag , v;
int u ;
int next ;
}edge[2*maxn] ;
int head[maxn] ;
int vis[maxn] ;
int nedge ;
int mi;
int st ;
int num ;
void addedge(int u , int v)
{
edge[nedge].u = u;
edge[nedge].v = v ;
edge[nedge].flag = 1;
edge[nedge].next = head[u] ;
head[u] = nedge++ ;
edge[nedge].u = v;
edge[nedge].v = u ;
edge[nedge].flag = 0;
edge[nedge].next = head[v] ;
head[v] = nedge++ ;
}
void init()
{
int nedge = 0;
memset(vis , 0 ,sizeof(vis)) ;
memset(head , -1 ,sizeof(head)) ;
memset(dp , 0 , sizeof(dp)) ;
}
void dfs(int u)
{
vis[u] = 1 ;
for(int i = head[u] ;i != -1 ;i = edge[i].next)
{
if(num == i)continue ;
int v = edge[i].v ;
if(vis[v])continue ;
if(edge[i].flag == 0)
dp[u]++;
dfs(v);
dp[u]+=dp[v] ;
}
}
void dfs_s(int u , int sum_1 ,int sum_0)
{
vis[u] = 1;
mi = min(dp[u] = (dp[st] - sum_0 + sum_1) , mi) ;
for(int i = head[u] ; i != -1;i = edge[i].next)
{
if(num == i)continue ;
int v = edge[i].v ;
if(vis[v])continue ;
if(edge[i].flag == 0)dfs_s(v , sum_1 ,sum_0 + 1) ;
else if(edge[i].flag == 1)dfs_s(v , sum_1 + 1, sum_0) ;
}
}
int main()
{
// freopen("input.txt" ,"r" ,stdin) ;
int n ;
while(~scanf("%d" ,&n))
{
int u , v;
init() ;
for(int i = 1;i < n;i++)
{
scanf("%d%d" ,&u ,&v) ;
addedge(u , v) ;
}
int ans = inf ;
int t = 0;
for(int i = 0;i < nedge;i++)
{
mi = inf;num = i;st = edge[i].u ;
memset(vis , 0 , sizeof(vis)) ;
memset(dp , 0 , sizeof(dp)) ;
dfs(edge[i].u) ;
memset(vis , 0 , sizeof(vis)) ;
dfs_s(edge[i].u , 0 , 0);
t += mi ;
if(i&1)ans = min(ans ,t),t =0;
}
if(ans == inf)puts("0");
else printf("%d\n" , ans) ;
}
return 0;
}
Codeforces Round #148 (Div. 1)C 树形dp
原文:http://blog.csdn.net/cq_pf/article/details/45270575