Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- typedef long double ld;
- int n;
- const int MXN=1e5+3;
- vector<int> adj[MXN];
- int dp[MXN][2][2];
- int dfs (int x,int pa,bool f,bool s)
- {
- if(dp[x][f][s]!=-1)return dp[x][f][s];
- int ans=0;
- bool pp=0;
- if((int)adj[x].size()>=3+f)
- pp=1;
- int ret=0;
- if(s)
- {
- for(auto u :adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,1,0);
- }
- return dp[x][f][s]=ans;
- }
- //1 take it
- for(auto u :adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,0,1);
- }
- ret=ans+pp;
- ans=0;
- for(auto u :adj[x])
- {
- if(u==pa)continue;
- if(pp)ans+=dfs(u,x,1,0);
- else ans+=dfs(u,x,0,0);
- }
- ret=max(ret,ans);
- return dp[x][f][s]=ret;
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- scanf("%d",&n);
- for(int i=1; i<n; i++)
- {
- int x,y;
- scanf("%d%d",&x,&y);
- adj[x].push_back(y);
- adj[y].push_back(x);
- }
- memset(dp,-1,sizeof dp);
- int ans=dfs(1,0,0,0);
- ans=max(ans,dfs(1,0,0,1));
- memset(dp,-1,sizeof dp);
- ans=max(ans,dfs(n,0,0,0));
- cout<<ans<<endl;
- for(int i=1;i<MXN;i++)adj[i].clear();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement