Advertisement
_rashed

UVA 12379

Jul 12th, 2022
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #define ll long long
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int OO = 1e9;
  6. const double EPS = 1e-9;
  7.  
  8. bool vis[10000];
  9. vector<vector<int>> graph;
  10. int n;
  11. int mx = -1;
  12. int mx_idx = -1;
  13.  
  14. void clr_vis() {
  15.     for(int i = 0; i < n; i++) {
  16.         vis[i] = 0;
  17.     }
  18. }
  19.  
  20. void dfs(int x, int c) {
  21.     vis[x] = 1;
  22.     if(graph[x].size() == 1 && (mx == -1 || mx < c)) {
  23.         mx = c;
  24.         mx_idx = x;
  25.     }
  26.     for(int e : graph[x]) {
  27.         if(!vis[e]) {
  28.             dfs(e,c+1);
  29.         }
  30.     }
  31. }
  32.  
  33. int main()
  34. {
  35.     ios_base::sync_with_stdio(false);
  36.     cin.tie(NULL);
  37.     cout.tie(NULL);
  38.     int t;
  39.     cin >> t;
  40.     while(t--) {
  41.         cin >> n;
  42.         graph.clear();
  43.         graph.resize(n);
  44.         for(int i = 0; i < n; i++) {
  45.             int m;
  46.             cin >> m;
  47.             for(int j = 0; j < m; j++) {
  48.                 int x;
  49.                 cin >> x;
  50.                 graph[i].push_back(x-1);
  51.             }
  52.         }
  53.         if(n == 1) {
  54.             cout << 0 << "\n";
  55.             continue;
  56.         }
  57.         clr_vis();
  58.         mx = -1;
  59.         mx_idx = -1;
  60.         for(int i = 0; i < n; i++) {
  61.             if(graph[i].size() == 1) {
  62.                 dfs(i,0);
  63.                 break;
  64.             }
  65.         }
  66.         clr_vis();
  67.         mx = -1;
  68.         dfs(mx_idx,0);
  69.         //cout << "mx is " << mx << "\n";
  70.         cout << mx + (n-(mx+1))*2 << "\n";
  71.     }
  72.     return 0;
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement