/*
Name:树的最大独立集(动态规划 dfs刷表)
Actor:HT
Time:2015年7月25日
Error Reporte:
1.vector的方便之处!!
attach[a].push_back(b);
attach[b].push_back(a);
直接放在最后,无需单独计数
}
*/
#include"stdio.h"
#include"string.h"
#include"iostream"
#include <algorithm>
#include <vector>
using namespace std;
#define MAXN 1005
int d[MAXN];
int sumC[MAXN]; //某根的所有儿子d和
int sumG[MAXN]; //某根的所有孙子d和
int fa[MAXN]; //记录每个点的父亲
vector<int>attach [MAXN]; //某点的所有直线相关点
void dfs(int p,int father)
{
fa[p] = father;
int i,j;
for(i = 0;i<attach[p].size();i++)
{
if(father == attach[p][i]) continue;
dfs(attach[p][i],p);
}
d[p] = (sumC[p]>sumG[p]+1?sumC[p]:sumG[p]+1);
//刷表!!!!!///
if(fa[p]!=-1)
{
sumC[fa[p]] +=d[p];
if(fa[fa[p]]!=-1) sumG[fa[fa[p]]] +=d[p];
}
//printf("%d = %d fa:%d sumC:%d sumG:%d\n",p,d[p],father,sumC[p],sumG[p]);
}
int main()
{
freopen("in.txt","r",stdin);
int i,j,n;
int a,b;
scanf("%d",&n);
for(i = 0; i < n-1; i++)
{
scanf("%d %d",&a,&b);
attach[a].push_back(b);
attach[b].push_back(a);
}
int ans=0;
for(i =0; i<n;i++)
{
memset(d,0,sizeof(d));
memset(sumC,0,sizeof(sumC));
memset(sumG,0,sizeof(sumG));
memset(fa,-1,sizeof(fa));
dfs(i,-1); //从最深的地方一点一点往上求,顺便刷表,故用dfs
ans = (d[i]>ans?d[i]:ans);
}
printf("%d\n",ans);
return 0;
}
//d[i] = 以i为根点时的最大独立集
//d[i] = max{sum(d[i-1]) , sum(d[i-2])+1}
//找儿子孙子做sum很麻烦,采用刷表发
/* 测试数据 ※从0开始到n-1结束※
8
0 1
1 4
0 2
0 3
1 5
5 6
5 7
答案是5
*/
[算法]树的最大独立集(动态规划 dfs刷表)
最新推荐文章于 2023-01-05 23:31:01 发布