Advertisement
jeff69

fofo

Sep 27th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef long double ld;
  5.  
  6. int n;
  7. const int MXN=1e5+3;
  8. vector<int> adj[MXN];
  9. int dp[MXN][2][2];
  10. int dfs (int x,int pa,bool f,bool s)
  11. {
  12.  
  13.     // delete the node
  14.     int ans=0;
  15.     int ret=0;
  16.     if(dp[x][f][s]!=-1)return dp[x][f][s];
  17.     if(s)
  18.     {
  19.         for(auto u :adj[x])
  20.         {
  21.             if(u==pa)continue;
  22.             ans+=dfs(u,x,1,0);
  23.  
  24.         }
  25.         return dp[x][f][s]=ans;
  26.     }
  27.     for(auto u :adj[x])
  28.     {
  29.         if(u==pa)continue;
  30.  
  31.         ans+=dfs(u,x,1,0);
  32.     }
  33.     ret=ans;
  34.     // check if it a star split it from the others
  35.     bool ok=0;
  36.     ok=(adj[x].size()>=3+f);
  37.     if(ok)
  38.     {
  39.         ans=1;
  40.         for(auto u: adj[x])
  41.         {
  42.             if(u==pa)continue;
  43.  
  44.             ans+=dfs(u,x,0,1);
  45.         }
  46.         ret=max(ret,ans);
  47.     }
  48.     // leave the node be
  49.     if(ok)return dp[x][f][s]=ret;
  50.     ans=0;
  51.     for(auto u: adj[x])
  52.     {
  53.         if(u==pa)continue;
  54.  
  55.         ans+=dfs(u,x,0,1);
  56.     }
  57.     int rr=ans;
  58.     for(auto u: adj[x])
  59.     {
  60.         if(u==pa)continue;
  61.  
  62.         rr=max(ans-dfs(u,x,0,1)+dfs(u,x,0,0),rr);
  63.  
  64.     }
  65.     ret=max(ret,rr);
  66.  
  67.     return dp[x][f][s]=ret;
  68.  
  69.  
  70. }
  71. int main()
  72. {
  73.     int t;
  74.     cin>>t;
  75.     while(t--)
  76.     {
  77.         scanf("%d",&n);
  78.         for(int i=1; i<n; i++)
  79.         {
  80.             int x,y;
  81.             scanf("%d%d",&x,&y);
  82.             adj[x].push_back(y);
  83.             adj[y].push_back(x);
  84.         }
  85.         memset(dp,-1,sizeof dp);
  86.         int ans=dfs(1,0,0,0);
  87.  
  88.         cout<<ans<<endl;
  89.         for(int i=1; i<MXN; i++)adj[i].clear();
  90.     }
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement