/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 45ms 33.312 MiB
#2 Accepted 57ms 33.316 MiB
#3 Time Exceeded ≥2100ms ≥33.477 MiB
#4 Time Exceeded ≥2102ms ≥33.48 MiB

Code

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

typedef tree<
  int,
  null_type,
  less_equal<int>,
  rb_tree_tag,
  tree_order_statistics_node_update
> ordered_set;

const int MAXN = 100005;

vector<int> g[MAXN];
int A[MAXN], B[MAXN];
int tin[MAXN], tout[MAXN], sz[MAXN], timer = 0;
int ans[MAXN];

// Segment Tree of PBDS
struct SegTree {

  ordered_set st[4 * MAXN];

  SegTree() {

  }

  void insert(int v, int l, int r, int pos, int val) {
    st[v].insert(val);
    if (l == r) return;
    int m = (l + r) / 2;
    if (pos <= m) insert(2 * v, l, m, pos, val);
    else insert(2 * v + 1, m + 1, r, pos, val);
  }

  void erase(int v, int l, int r, int pos, int val) {
    st[v].erase(st[v].upper_bound(val));
    if (l == r) return;
    int m = (l + r) / 2;
    if (pos <= m) erase(2 * v, l, m, pos, val);
    else erase(2 * v + 1, m + 1, r, pos, val);
  }

  int query(int v, int l, int r, int ql, int qr, int lo, int hi) {
    if (r < ql || l > qr) return 0;
    if (ql <= l && r <= qr) {
      return st[v].order_of_key(hi + 1) - st[v].order_of_key(lo);
    }
    int m = (l + r) / 2;
    return query(2 * v, l, m, ql, qr, lo, hi) +
           query(2 * v + 1, m + 1, r, ql, qr, lo, hi);
  }

  void clear() {
    for (int i = 0; i < 4 * MAXN; ++i) st[i].clear();
  }
};

SegTree seg;

void dfs(int u, int p) {
  tin[u] = ++timer;
  sz[u] = 1;

  for (int v : g[u]) {
    if (v == p) continue;
    dfs(v, u);
    sz[u] += sz[v];
  }

  tout[u] = timer;

  if (B[A[u]]) seg.erase(1, 1, MAXN, A[u], B[A[u]]);
  B[A[u]] = tout[u];
  seg.insert(1, 1, MAXN, A[u], tout[u]);

  int count = seg.query(1, 1, MAXN, 1, sz[u], tin[u], tout[u]);
  ans[u] = sz[u] - count;
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int N; cin >> N;

    // Reset global state
    timer = 0;
    seg.clear();

    for (int i = 1; i <= N; ++i) {
      g[i].clear();
      B[i] = 0;
      ans[i] = 0;
      tin[i] = tout[i] = sz[i] = 0;
    }

    for (int i = 1; i <= N; ++i) cin >> A[i];
    for (int i = 1; i < N; ++i) {
      int u, v; cin >> u >> v;
      g[u].push_back(v);
      g[v].push_back(u);
    }

    dfs(1, 0);

    int q;
    cin >> q;
    for (int i = 1; i <= q; ++i) {
      int x;
      cin >> x;
      cout << ans[x] << '\n';
    }
  }
}

Information

Submit By
Type
Submission
Problem
P1157 H. Roy and Tree Permutation
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-15 20:00:55
Judged At
2025-07-15 20:00:55
Judged By
Score
10
Total Time
≥2102ms
Peak Memory
≥33.48 MiB