Submission #933660

#TimeUsernameProblemLanguageResultExecution timeMemory
933660NeroZeinJail (JOI22_jail)C++17
49 / 100
5060 ms28252 KiB
#include "bits/stdc++.h"
using namespace std;

#ifdef Nero
#include "Deb.h"
#else
#define debug(...)
#endif

const int LOG = 18;
const int N = 120005;

bool tv[N];
int cnt[N]; 
int dep[N];
bool busy[N];
int s[N], t[N];
int up[LOG][N];
vector<int> g[N];

void dfs(int v, int p) {
  for (int u : g[v]) {
    if (u == p) continue;
    up[0][u] = v;
    for (int j = 1; j < LOG; ++j) {
      up[j][u] = up[j - 1][up[j - 1][u]];
    }
    dep[u] = dep[v] + 1;
    dfs(u, v);
  }
}

int lca(int u, int v) {
  if (dep[u] < dep[v]) swap(u, v);
  for (int j = 0; j < LOG; ++j) {
    if ((dep[u] - dep[v]) >> j & 1) {
      u = up[j][u];
    }
  }
  if (u == v) return v;
  for (int j = LOG - 1; j >= 0; --j) {
    if (up[j][u] != up[j][v]) {
      u = up[j][u]; v = up[j][v];
    }
  }
  return up[0][v];
}

void mark(int u, int v, int w) {
  vector<int> tmp;
  int lc = lca(u, v);
  while (true) {
    tmp.push_back(u);
    tv[u] = true;
    cnt[u] += w;
    if (u == lc) break;
    u = up[0][u];
  }
  while (!tv[v]) {
    cnt[v] += w;
    v = up[0][v];
  }
  for (int i : tmp) tv[i] = false; 
}

bool check(int u, int v) {
  bool ok = cnt[v] == 1; 
  int lc = lca(u, v);
  while (u != lc) {
    u = up[0][u];
    ok &= !busy[u];
  }
  while (v != lc) {
    ok &= !busy[v]; 
    v = up[0][v];
  }
  return ok;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int tt;
  cin >> tt;
  while (tt--) {
    int n;
    cin >> n;
    for(int i = 0; i < n - 1; ++i) {
      int u, v;
      cin >> u >> v;
      g[u].push_back(v);
      g[v].push_back(u);
    }
    dfs(1, 0);
    int m;
    cin >> m;
    for (int i = 0; i < m; ++i) {
      cin >> s[i] >> t[i];
      mark(s[i], t[i], 1);
      busy[s[i]] = true; 
    }
    bool ok = true; 
    for (int rep = 0; rep < m; ++rep) {
      bool f = false; 
      for (int i = 0; i < m; ++i) {
        if (!busy[s[i]]) continue; 
        if (check(s[i], t[i])) {
          f = true;
          busy[s[i]] = false; 
          mark(s[i], t[i], -1);
          break; 
        }
      }
      if (!f) {
        ok = false;
        break;
      }
    }
    for (int i = 1; i <= n; ++i) {
      g[i].clear();
      cnt[i] = 0; 
      busy[i] = false; 
    }
    cout << (ok ? "Yes" : "No") << '\n';
  }
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...