略微超时,玄关求调,pwp

P3806 【模板】点分治 1

Heldivis @ 2024-10-11 11:00:17

rt,TLE on #8, 329ms TLE on #10 263ms

改链式前向猩 WA 了

#include <algorithm>
#include <cstdio>
#include <vector>
#define re register
struct FIO {
  inline char gc() {
    static const int L = 1 << 10 | 1;
    static char buf[L], *s, *t;
    return (s == t) && (t = (s = buf) + fread(buf, 1, L, stdin)),
           s == t ? -1 : *s++;
  }
  inline FIO &operator>>(int &x) {
    static char c11;
    for (c11 = gc(); c11 < 48; c11 = gc())
      if (c11 == -1) return *this;
    for (x = 0; c11 > 47; c11 = gc()) x = x * 10 + (c11 ^ '0');
    return *this;
  }
} fin;
inline int max(const int &x, const int &y) { return x > y ? x : y; }

const int N = 1E4 + 1;
int n, q, dis[N], k[N];
std::vector<std::pair<int, int> > e[N];
bool p[N], ans[N];

int rt, maxx, siz[N], sz;
void Get(int x, int fa) {
  int sum = 0;
  siz[x] = 1;
  for (auto &[y, w] : e[x])
    if (!p[y] && y != fa) Get(y, x), siz[x] += siz[y], sum = max(sum, siz[y]);
  sum = max(sum, sz - siz[x]);
  if (sum < maxx) maxx = sum, rt = x;
}

int tot, node[N], d[N], anc[N];

void Dis(int x, int fa, int dis, int ff) {
  node[++tot] = x, d[x] = dis, anc[x] = ff;
  for (auto &[y, w] : e[x])
    if (!p[y] && y != fa) Dis(y, x, dis + w, ff);
}

void Calc(int x) {
  tot = 0, node[++tot] = x, d[x] = 0, anc[x] = x;
  for (auto &[y, w] : e[x])
    if (!p[y]) Dis(y, x, w, y);
  std::sort(node + 1, node + 1 + tot,
            [&](const int &x, const int &y) { return d[x] < d[y]; });
  for (int i = 1, l, r; i <= q; ++i)
    if (!ans[i]) {
      l = 1, r = tot;
      while (l < r) {
        if (d[node[l]] + d[node[r]] > k[i])
          --r;
        else if (d[node[l]] + d[node[r]] < k[i])
          ++l;
        else if (anc[node[l]] == anc[node[r]])
          d[node[r]] == d[node[r - 1]] ? --r : ++l;
        else
          ans[i] = true, r = 0;
      }
    }
}

void Solve(int x) {
  p[x] = true, Calc(x);
  for (auto &[y, w] : e[x])
    if (!p[y]) rt = y, sz = siz[y], maxx = N, Get(x, x), Solve(rt);
}

signed main() {
  fin >> n >> q;
  for (re int i = 1, x, y, w; i < n; i++)
    fin >> x >> y >> w, e[x].emplace_back(y, w), e[y].emplace_back(x, w);
  for (re int i = 1; i <= q; ++i) fin >> k[i];
  sz = n, maxx = N, Get(1, 1), Solve(rt);
  for (re int i = 1; i <= q; i++) puts(ans[i] ? "AYE" : "NAY");
  return 0;
}

by bamboo12345 @ 2024-10-11 11:12:53

吐槽一句,这马蜂太奇葩了,我的dev直接挂了根本跑不了,开的是 c++14

就一般来说如果超时了那就是重心的问题,建议就是每次处理出 sz 后再去跑重心,我之前尝试这么写过好像 sz 的维护会出现一些 bug,不知道是不是我写丑了。这一点常数贪了不如不贪


by bamboo12345 @ 2024-10-11 11:13:19

有错可以踹我我紫衫,毕竟我是真的跑不了这代码()


by Redamancy_Lydic @ 2024-10-11 11:14:16

@bamboo1030 : 这是C17的


by bamboo12345 @ 2024-10-11 11:15:49

@Redamancy_Lydic c17 devc++ 没有()


|