matbensch

TreeHoppingSolution

Mar 21st, 2022
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int n;
  7. vector<int> arr;
  8. vector<int> par;
  9. vector<bool> vis;
  10. vector<vector<int>> adj;
  11.  
  12. void dfs(int p,int u)
  13. {
  14.     par[u] = p;
  15.     vis[u] = true;
  16.     for(int v:adj[u])
  17.     {
  18.         if(!vis[v]) dfs(u,v);
  19.     }
  20. }
  21.  
  22. int main()
  23. {
  24.     int t;
  25.     cin>>t;
  26.     int outs = 0;
  27.     while(t--)
  28.     {
  29.         cin>>n;
  30.         arr.assign(n, -1);
  31.         par.assign(n, -1);
  32.         vis.assign(n, false);
  33.         adj.assign(n, vector<int>(0));
  34.         for(int i=0;i<n-1;i++)
  35.         {
  36.             int u,v;
  37.             cin>>u>>v;
  38.             adj[u-1].push_back(v-1);
  39.             adj[v-1].push_back(u-1);
  40.         }
  41.  
  42.         dfs(-1,0);
  43.  
  44.         for(int i=0;i<n;i++)
  45.         {
  46.             cin>>arr[i];
  47.             arr[i]--;
  48.         }
  49.  
  50.         bool pos = true;
  51.  
  52.         for(int i=0;i<n-1;i++)
  53.         {
  54.             int a = arr[i];
  55.             int b = arr[i+1];
  56.  
  57.             vector<int> path1,path2;
  58.  
  59.             int cur = a;
  60.             for(int i=0;i<5;i++)
  61.             {
  62.                 path1.push_back(cur);
  63.                 cur = par[cur];
  64.                 if(cur==-1) break;
  65.             }
  66.  
  67.             cur = b;
  68.             for(int i=0;i<5;i++)
  69.             {
  70.                 path2.push_back(cur);
  71.                 cur = par[cur];
  72.                 if(cur==-1) break;
  73.             }
  74.  
  75.             bool close = false;
  76.             for(int i=0;i<path1.size();i++)
  77.             {
  78.                 for(int j=0;j<path2.size();j++)
  79.                 {
  80.                     if(path1[i]==path2[j] && i+j<=3) close = true;
  81.                 }
  82.                 if(close) break;
  83.             }
  84.  
  85.             if(!close)
  86.             {
  87.                 pos = false;
  88.                 break;
  89.             }
  90.  
  91.         }
  92.  
  93.         cout << pos << '\n';
  94.         outs++;
  95.  
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment