题目:
思路:
分析题意会发现,每个所选择的点只能有两条分支长度大于 2, 其他长度只能为1.
我们考虑树形dp,对于每个节点我们先考虑他和他的两个儿子分支构成的结果,在更新其分支的最大值,向上传递
Ac_Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#define fir first
#define sec second
using namespace std;
const int maxn = 3e5+7;
int n,e;
int edge[maxn<<1],nex[maxn<<1],head[maxn];
int dp[maxn];
int sz[maxn];
int ans;
void add(int l,int r) {
edge[++e] = r;
nex[e] = head[l];
head[l] = e;
}
void dfs(int u,int f) {
sz[u] = 0;
int Max = 0,CMax = 0;
for(int i=head[u];i;i=nex[i]) {
int v = edge[i];
if(v == f) continue;
dfs(v,u);
sz[u]++;
if(Max < dp[v]) {
CMax = Max;
Max = dp[v];
}
else if(CMax < dp[v]) CMax = dp[v];
}
if(f == 0) {
if(sz[u]==0) ans=max(ans,1);
else if(sz[u] ==1) ans = max(Max+1,ans);
else if(sz[u] >=2) ans = max(CMax+Max+sz[u]-1,ans);
}
else {
if(sz[u]==0) ans = max(ans,1);
else if(sz[u] == 1) ans = max(Max+2,ans);
else if(sz[u] >= 2) {
ans = max(Max+CMax+sz[u],ans);
}
}
if(sz[u] != 0)dp[u] = Max+sz[u];
else dp[u] = 1;
}
int main() {
int t;
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
e = 0,ans = 0;
for(int i=0;i<=n;i++) head[i] = 0;
for(int i=1;i<n;i++) {
int l,r;
scanf("%d%d",&l,&r);
add(l,r);
add(r,l);
}
dfs(1,0);
printf("%d\n",ans);
}
return 0;
}