G. Tree Destruction
链接
思路
dp。就是一个dfs往下遍历。
显然最后的答案是路径上所有点的度-2的和,最后加上2.
注意需要记录并替换两个的最大值,但是只需要返回一端的最大值。
这题不知道为什么卡\(long long\)不让用,只能用\(int\)
代码
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
int n;
const int N = 2e5 + 10;
const int INF = -1e9;
vector<int>G[N];
int ans;
bool cmp(int a, int b) {
return a > b;
}
int dfs(int now, int fa) {
vector<int>vt;
for (int v : G[now]) {
if (v == fa)continue;
vt.push_back(dfs(v, now));
}
if (vt.empty()) { ans = max(ans, (int) - 1); return -1; }
int ret = INF;
int db = INF;
if (vt.size() == 1) {
if (vt[0] > 0)ret = G[now].size() - 2 + vt[0];
else ret = G[now].size() - 2;
}
else {
sort(vt.begin(), vt.end(), cmp);
db = G[now].size() - 2 + vt[0] + vt[1];
if (vt[0] > 0)ret = G[now].size() - 2 + vt[0];
else ret = G[now].size() - 2;
}
ans = max(ans, db);
ans = max(ans, ret);
return ret;
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i++)G[i].clear();
for (int i = 1; i < n; i++) {
int u, v; cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
ans = INF;
int answ = dfs(1, 0);
ans = max(ans, answ);
cout << ans+2 << '\n';
}
signed main() {
IOS;
/**/int t;
cin >> t;
if(t>0)
while (t--)
solve();
else {
}
return 0;
}