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)
- {
- // delete the node
- int ans=0;
- int ret=0;
- if(dp[x][f][s]!=-1)return dp[x][f][s];
- if(s)
- {
- for(auto u :adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,1,0);
- }
- return dp[x][f][s]=ans;
- }
- for(auto u :adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,1,0);
- }
- ret=ans;
- // check if it a star split it from the others
- bool ok=0;
- ok=(adj[x].size()>=3+f);
- if(ok)
- {
- ans=1;
- for(auto u: adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,0,1);
- }
- ret=max(ret,ans);
- }
- // leave the node be
- if(ok)return dp[x][f][s]=ret;
- ans=0;
- for(auto u: adj[x])
- {
- if(u==pa)continue;
- ans+=dfs(u,x,0,1);
- }
- int rr=ans;
- for(auto u: adj[x])
- {
- if(u==pa)continue;
- rr=max(ans-dfs(u,x,0,1)+dfs(u,x,0,0),rr);
- }
- ret=max(ret,rr);
- 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);
- 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