QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#112788 | #5418. Color the Tree | maspy | AC ✓ | 295ms | 40688kb | C++23 | 28.2kb | 2023-06-13 14:56:47 | 2023-06-13 14:56:51 |
Judging History
answer
#line 1 "library/my_template.hpp"
#if defined(LOCAL)
#include <my_template_compiled.hpp>
#else
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define overload4(a, b, c, d, e, ...) e
#define overload3(a, b, c, d, ...) d
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) overload3(__VA_ARGS__, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) \
for (ll t = (s); t >= 0; t = (t == 0 ? -1 : (t - 1) & (s)))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
template <typename T, typename U>
T SUM(const vector<U> &A) {
T sum = 0;
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()
template <typename T>
T POP(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T POP(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T POP(pqg<T> &que) {
assert(!que.empty());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T POP(vc<T> &que) {
assert(!que.empty());
T a = que.back();
que.pop_back();
return a;
}
template <typename F>
ll binary_search(F check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return ok;
}
template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
FOR(iter) {
double x = (ok + ng) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return (ok + ng) / 2;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
return A;
}
template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
// stable sort
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(len(A));
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
vc<T> B(len(I));
FOR(i, len(I)) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
#define FASTIO
// クラスが read(), print() を持っているかを判定するメタ関数
struct has_write_impl {
template <class T>
static auto check(T &&x) -> decltype(x.write(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {
};
struct has_read_impl {
template <class T>
static auto check(T &&x) -> decltype(x.read(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};
struct Scanner {
FILE *fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <typename T,
typename enable_if<has_read<T>::value>::type * = nullptr>
inline bool read_single(T &x) {
x.read();
return true;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
bool read_single(char &ref) {
string s;
if (!read_single(s) || s.size() != 1) return false;
ref = s[0];
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <size_t N = 0, typename T>
void read_single_tuple(T &t) {
if constexpr (N < std::tuple_size<T>::value) {
auto &x = std::get<N>(t);
read_single(x);
read_single_tuple<N + 1>(t);
}
}
template <class... T>
bool read_single(tuple<T...> &tpl) {
read_single_tuple(tpl);
return true;
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
void write(const long double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
template <typename T,
typename enable_if<has_write<T>::value>::type * = nullptr>
inline void write(T x) {
x.write();
}
template <class T>
void write(const vector<T> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> val) {
write(val.first);
write(' ');
write(val.second);
}
template <size_t N = 0, typename T>
void write_tuple(const T t) {
if constexpr (N < std::tuple_size<T>::value) {
if constexpr (N > 0) { write(' '); }
const auto x = std::get<N>(t);
write(x);
write_tuple<N + 1>(t);
}
}
template <class... T>
bool write(tuple<T...> tpl) {
write_tuple(tpl);
return true;
}
template <class T, size_t S>
void write(const array<T, S> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
void write(i128 val) {
string s;
bool negative = 0;
if (val < 0) {
negative = 1;
val = -val;
}
while (val) {
s += '0' + int(val % 10);
val /= 10;
}
if (negative) s += "-";
reverse(all(s));
if (len(s) == 0) s = "0";
write(s);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
} // namespace fastio
using fastio::print;
using fastio::flush;
using fastio::read;
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define CHAR(...) \
char __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "library/graph/base.hpp"
template <typename T>
struct Edge {
int frm, to;
T cost;
int id;
};
template <typename T = int, bool directed = false>
struct Graph {
int N, M;
using cost_type = T;
using edge_type = Edge<T>;
vector<edge_type> edges;
vector<int> indptr;
vector<edge_type> csr_edges;
vc<int> vc_deg, vc_indeg, vc_outdeg;
bool prepared;
class OutgoingEdges {
public:
OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}
const edge_type* begin() const {
if (l == r) { return 0; }
return &G->csr_edges[l];
}
const edge_type* end() const {
if (l == r) { return 0; }
return &G->csr_edges[r];
}
private:
const Graph* G;
int l, r;
};
bool is_prepared() { return prepared; }
constexpr bool is_directed() { return directed; }
Graph() : N(0), M(0), prepared(0) {}
Graph(int N) : N(N), M(0), prepared(0) {}
void resize(int n) { N = n; }
void add(int frm, int to, T cost = 1, int i = -1) {
assert(!prepared);
assert(0 <= frm && 0 <= to && to < N);
if (i == -1) i = M;
auto e = edge_type({frm, to, cost, i});
edges.eb(e);
++M;
}
// wt, off
void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }
void read_graph(int M, bool wt = false, int off = 1) {
for (int m = 0; m < M; ++m) {
INT(a, b);
a -= off, b -= off;
if (!wt) {
add(a, b);
} else {
T c;
read(c);
add(a, b, c);
}
}
build();
}
void read_parent(int off = 1) {
for (int v = 1; v < N; ++v) {
INT(p);
p -= off;
add(p, v);
}
build();
}
void build() {
assert(!prepared);
prepared = true;
indptr.assign(N + 1, 0);
for (auto&& e: edges) {
indptr[e.frm + 1]++;
if (!directed) indptr[e.to + 1]++;
}
for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }
auto counter = indptr;
csr_edges.resize(indptr.back() + 1);
for (auto&& e: edges) {
csr_edges[counter[e.frm]++] = e;
if (!directed)
csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
}
}
OutgoingEdges operator[](int v) const {
assert(prepared);
return {this, indptr[v], indptr[v + 1]};
}
vc<int> deg_array() {
if (vc_deg.empty()) calc_deg();
return vc_deg;
}
pair<vc<int>, vc<int>> deg_array_inout() {
if (vc_indeg.empty()) calc_deg_inout();
return {vc_indeg, vc_outdeg};
}
int deg(int v) {
if (vc_deg.empty()) calc_deg();
return vc_deg[v];
}
int in_deg(int v) {
if (vc_indeg.empty()) calc_deg_inout();
return vc_indeg[v];
}
int out_deg(int v) {
if (vc_outdeg.empty()) calc_deg_inout();
return vc_outdeg[v];
}
void debug() {
print("Graph");
if (!prepared) {
print("frm to cost id");
for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);
} else {
print("indptr", indptr);
print("frm to cost id");
FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);
}
}
private:
void calc_deg() {
assert(vc_deg.empty());
vc_deg.resize(N);
for (auto&& e: edges) vc_deg[e.frm]++, vc_deg[e.to]++;
}
void calc_deg_inout() {
assert(vc_indeg.empty());
vc_indeg.resize(N);
vc_outdeg.resize(N);
for (auto&& e: edges) { vc_indeg[e.to]++, vc_outdeg[e.frm]++; }
}
};
#line 3 "library/graph/tree.hpp"
// HLD euler tour をとっていろいろ。
// 木以外、非連結でも dfs 順序や親がとれる。
template <typename GT>
struct TREE {
using Graph_type = GT;
GT &G;
using WT = typename GT::cost_type;
int N;
bool hld;
vector<int> LID, RID, head, V, parent;
vc<int> depth;
vc<WT> depth_weighted;
TREE(GT &G, int r = -1, bool hld = 1)
: G(G),
N(G.N),
hld(hld),
LID(G.N),
RID(G.N),
head(G.N, r),
V(G.N),
parent(G.N, -1),
depth(G.N, -1),
depth_weighted(G.N, 0) {
assert(G.is_prepared());
int t1 = 0;
if (r != -1) {
dfs_sz(r, -1);
dfs_hld(r, t1);
} else {
for (int r = 0; r < N; ++r) {
if (parent[r] == -1) {
head[r] = r;
dfs_sz(r, -1);
dfs_hld(r, t1);
}
}
}
}
void dfs_sz(int v, int p) {
auto &sz = RID;
parent[v] = p;
depth[v] = (p == -1 ? 0 : depth[p] + 1);
sz[v] = 1;
int l = G.indptr[v], r = G.indptr[v + 1];
auto &csr = G.csr_edges;
// 使う辺があれば先頭にする
for (int i = r - 2; i >= l; --i) {
if (hld && depth[csr[i + 1].to] == -1) swap(csr[i], csr[i + 1]);
}
int hld_sz = 0;
for (int i = l; i < r; ++i) {
auto e = csr[i];
if (depth[e.to] != -1) continue;
depth_weighted[e.to] = depth_weighted[v] + e.cost;
dfs_sz(e.to, v);
sz[v] += sz[e.to];
if (hld && chmax(hld_sz, sz[e.to]) && l < i) { swap(csr[l], csr[i]); }
}
}
void dfs_hld(int v, int ×) {
LID[v] = times++;
RID[v] += LID[v];
V[LID[v]] = v;
bool heavy = true;
for (auto &&e: G[v]) {
if (depth[e.to] <= depth[v]) continue;
head[e.to] = (heavy ? head[v] : e.to);
heavy = false;
dfs_hld(e.to, times);
}
}
vc<int> heavy_path_at(int v) {
vc<int> P = {v};
while (1) {
int a = P.back();
for (auto &&e: G[a]) {
if (e.to != parent[a] && head[e.to] == v) {
P.eb(e.to);
break;
}
}
if (P.back() == a) break;
}
return P;
}
int e_to_v(int eid) {
auto e = G.edges[eid];
return (parent[e.frm] == e.to ? e.frm : e.to);
}
int ELID(int v) { return 2 * LID[v] - depth[v]; }
int ERID(int v) { return 2 * RID[v] - depth[v] - 1; }
/* k: 0-indexed */
int LA(int v, int k) {
assert(k <= depth[v]);
while (1) {
int u = head[v];
if (LID[v] - k >= LID[u]) return V[LID[v] - k];
k -= LID[v] - LID[u] + 1;
v = parent[u];
}
}
int LCA(int u, int v) {
for (;; v = parent[head[v]]) {
if (LID[u] > LID[v]) swap(u, v);
if (head[u] == head[v]) return u;
}
}
int lca(int u, int v) { return LCA(u, v); }
int la(int u, int v) { return LA(u, v); }
int subtree_size(int v) { return RID[v] - LID[v]; }
int dist(int a, int b) {
int c = LCA(a, b);
return depth[a] + depth[b] - 2 * depth[c];
}
WT dist(int a, int b, bool weighted) {
assert(weighted);
int c = LCA(a, b);
return depth_weighted[a] + depth_weighted[b] - WT(2) * depth_weighted[c];
}
// a is in b
bool in_subtree(int a, int b) { return LID[b] <= LID[a] && LID[a] < RID[b]; }
int jump(int a, int b, ll k) {
if (k == 1) {
if (a == b) return -1;
return (in_subtree(b, a) ? LA(b, depth[b] - depth[a] - 1) : parent[a]);
}
int c = LCA(a, b);
int d_ac = depth[a] - depth[c];
int d_bc = depth[b] - depth[c];
if (k > d_ac + d_bc) return -1;
if (k <= d_ac) return LA(a, k);
return LA(b, d_ac + d_bc - k);
}
vc<int> collect_child(int v) {
vc<int> res;
for (auto &&e: G[v])
if (e.to != parent[v]) res.eb(e.to);
return res;
}
vc<pair<int, int>> get_path_decomposition(int u, int v, bool edge) {
// [始点, 終点] の"閉"区間列。
vc<pair<int, int>> up, down;
while (1) {
if (head[u] == head[v]) break;
if (LID[u] < LID[v]) {
down.eb(LID[head[v]], LID[v]);
v = parent[head[v]];
} else {
up.eb(LID[u], LID[head[u]]);
u = parent[head[u]];
}
}
if (LID[u] < LID[v]) down.eb(LID[u] + edge, LID[v]);
elif (LID[v] + edge <= LID[u]) up.eb(LID[u], LID[v] + edge);
reverse(all(down));
up.insert(up.end(), all(down));
return up;
}
vc<int> restore_path(int u, int v) {
vc<int> P;
for (auto &&[a, b]: get_path_decomposition(u, v, 0)) {
if (a <= b) {
FOR(i, a, b + 1) P.eb(V[i]);
} else {
FOR_R(i, b, a + 1) P.eb(V[i]);
}
}
return P;
}
};
#line 1 "library/graph/compress_tree.hpp"
// (圧縮された木の頂点ラベルたち、グラフ)
template <typename TREE>
pair<vc<int>, typename TREE::Graph_type> compress_tree(TREE& tree, vc<int> V) {
// 大事な点をリストアップする
// もともとの根は含まれるようにする
{
vc<int> VV = V;
sort(all(V), [&](auto& x, auto& y) { return tree.LID[x] < tree.LID[y]; });
FOR(i, len(V) - 1) { VV.eb(tree.lca(V[i], V[i + 1])); }
VV.eb(tree.lca(V[0], V.back()));
VV.eb(tree.V[0]);
UNIQUE(VV);
V = VV;
sort(all(V), [&](auto& x, auto& y) { return tree.LID[x] < tree.LID[y]; });
}
// 辺を張ってグラフを作る
int n = len(V);
using GT = typename TREE::Graph_type;
using WT = typename GT::cost_type;
GT G(n);
vc<int> st = {0};
FOR(i, 1, n) {
while (1) {
int p = V[st.back()];
int v = V[i];
if (tree.in_subtree(v, p)) break;
st.pop_back();
}
int p = V[st.back()];
int v = V[i];
WT d = tree.depth_weighted[v] - tree.depth_weighted[p];
G.add(st.back(), i, d);
st.eb(i);
}
G.build();
return {V, G};
}
#line 2 "library/ds/segtree/segtree.hpp"
template <class Monoid>
struct SegTree {
using MX = Monoid;
using X = typename MX::value_type;
using value_type = X;
vc<X> dat;
int n, log, size;
SegTree() {}
SegTree(int n) { build(n); }
template <typename F>
SegTree(int n, F f) {
build(n, f);
}
SegTree(const vc<X>& v) { build(v); }
void build(int m) {
build(m, [](int i) -> X { return MX::unit(); });
}
void build(const vc<X>& v) {
build(len(v), [&](int i) -> X { return v[i]; });
}
template <typename F>
void build(int m, F f) {
n = m, log = 1;
while ((1 << log) < n) ++log;
size = 1 << log;
dat.assign(size << 1, MX::unit());
FOR(i, n) dat[size + i] = f(i);
FOR_R(i, 1, size) update(i);
}
X get(int i) { return dat[size + i]; }
vc<X> get_all() { return {dat.begin() + size, dat.begin() + size + n}; }
void update(int i) { dat[i] = Monoid::op(dat[2 * i], dat[2 * i + 1]); }
void set(int i, const X& x) {
assert(i < n);
dat[i += size] = x;
while (i >>= 1) update(i);
}
void multiply(int i, const X& x) {
assert(i < n);
i += size;
dat[i] = Monoid::op(dat[i], x);
while (i >>= 1) update(i);
}
X prod(int L, int R) {
assert(0 <= L && L <= R && R <= n);
X vl = Monoid::unit(), vr = Monoid::unit();
L += size, R += size;
while (L < R) {
if (L & 1) vl = Monoid::op(vl, dat[L++]);
if (R & 1) vr = Monoid::op(dat[--R], vr);
L >>= 1, R >>= 1;
}
return Monoid::op(vl, vr);
}
X prod_all() { return dat[1]; }
template <class F>
int max_right(F check, int L) {
assert(0 <= L && L <= n && check(Monoid::unit()));
if (L == n) return n;
L += size;
X sm = Monoid::unit();
do {
while (L % 2 == 0) L >>= 1;
if (!check(Monoid::op(sm, dat[L]))) {
while (L < size) {
L = 2 * L;
if (check(Monoid::op(sm, dat[L]))) { sm = Monoid::op(sm, dat[L++]); }
}
return L - size;
}
sm = Monoid::op(sm, dat[L++]);
} while ((L & -L) != L);
return n;
}
template <class F>
int min_left(F check, int R) {
assert(0 <= R && R <= n && check(Monoid::unit()));
if (R == 0) return 0;
R += size;
X sm = Monoid::unit();
do {
--R;
while (R > 1 && (R % 2)) R >>= 1;
if (!check(Monoid::op(dat[R], sm))) {
while (R < size) {
R = 2 * R + 1;
if (check(Monoid::op(dat[R], sm))) { sm = Monoid::op(dat[R--], sm); }
}
return R + 1 - size;
}
sm = Monoid::op(dat[R], sm);
} while ((R & -R) != R);
return 0;
}
// モノイドが可換なら、prod_{l<=i<r} A[i xor x] が計算可能
X xor_prod(int l, int r, int xor_val) {
static_assert(Monoid::commute);
X x = Monoid::unit();
for (int k = 0; k < log + 1; ++k) {
if (l >= r) break;
if (l & 1) { x = Monoid::op(x, dat[(size >> k) + ((l++) ^ xor_val)]); }
if (r & 1) { x = Monoid::op(x, dat[(size >> k) + ((--r) ^ xor_val)]); }
l /= 2, r /= 2, xor_val /= 2;
}
return x;
}
};
#line 2 "library/alg/monoid/min.hpp"
template <class X>
struct Monoid_Min {
using value_type = X;
static constexpr X op(const X &x, const X &y) noexcept { return min(x, y); }
static constexpr X unit() { return numeric_limits<X>::max(); }
static constexpr bool commute = true;
};
#line 3 "library/graph/shortest_path/dijkstra.hpp"
template <typename T, typename Graph>
pair<vc<T>, vc<int>> dijkstra(Graph& G, int v, T INF) {
auto N = G.N;
vector<T> dist(N, INF);
vector<int> par(N, -1);
using P = pair<T, int>;
priority_queue<P, vector<P>, greater<P>> que;
dist[v] = 0;
que.emplace(0, v);
while (!que.empty()) {
auto [dv, v] = que.top();
que.pop();
if (dv > dist[v]) continue;
for (auto&& e: G[v]) {
if (chmin(dist[e.to], dist[e.frm] + e.cost)) {
par[e.to] = e.frm;
que.emplace(dist[e.to], e.to);
}
}
}
return {dist, par};
}
// 多点スタート。[dist, par, root]
template <typename T, typename Graph>
tuple<vc<T>, vc<int>, vc<int>> dijkstra(Graph& G, vc<int> vs, T INF) {
assert(G.is_prepared());
int N = G.N;
vc<ll> dist(N, INF);
vc<int> par(N, -1);
vc<int> root(N, -1);
using P = pair<T, int>;
priority_queue<P, vector<P>, greater<P>> que;
for (auto&& v: vs) {
dist[v] = 0;
root[v] = v;
que.emplace(T(0), v);
}
while (!que.empty()) {
auto [dv, v] = que.top();
que.pop();
if (dv > dist[v]) continue;
for (auto&& e: G[v]) {
if (chmin(dist[e.to], dist[e.frm] + e.cost)) {
root[e.to] = root[e.frm];
par[e.to] = e.frm;
que.push(mp(dist[e.to], e.to));
}
}
}
return {dist, par, root};
}
#line 8 "main.cpp"
void solve() {
LL(N);
Graph<int, 0> G(N);
VEC(int, A, N);
SegTree<Monoid_Min<int>> seg0(A);
G.read_tree();
TREE<decltype(G)> tree(G);
auto& dep = tree.depth;
vvc<int> dep_to_v(N);
FOR(i, N) {
int v = tree.V[i];
dep_to_v[dep[v]].eb(v);
}
ll ANS = 0;
FOR(d, N) {
auto& V = dep_to_v[d];
if (V.empty()) continue;
int n = len(V);
auto [W, H] = compress_tree<decltype(tree)>(tree, V);
vc<int> euler(n);
FOR(i, n) euler[i] = tree.LID[V[i]];
// cost, l, r
vc<tuple<int, int, int>> dat;
for (auto&& a: W) {
int l = tree.LID[a], r = tree.RID[a];
r = LB(euler, r);
l = LB(euler, l);
int da = dep[a];
int cost = seg0.prod(d - da, d + 1);
dat.eb(cost, l, r);
}
// dijkstra graph
Graph<ll, 1> X(n + 1);
for (auto&& [x, l, r]: dat) X.add(l, r, x);
FOR(i, n) X.add(i + 1, i, 0);
X.build();
const ll INF = 1LL << 60;
auto [dist, par] = dijkstra(X, 0, INF);
ANS += dist[n];
}
print(ANS);
}
signed main() {
INT(T);
FOR(T) solve();
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 3424kb
input:
3 4 10 15 40 1 1 2 2 3 2 4 5 10 5 1 100 1000 1 2 2 3 2 4 4 5 4 1000 200 10 8 1 2 2 3 3 4
output:
35 17 1218
result:
ok 3 number(s): "35 17 1218"
Test #2:
score: 0
Accepted
time: 101ms
memory: 3524kb
input:
3000 54 43 44 11 49 17 14 7 30 35 12 34 14 15 8 29 47 30 31 39 17 26 23 26 45 34 50 49 13 35 18 29 15 13 44 47 5 22 20 19 46 30 22 26 13 47 46 43 27 48 48 13 14 30 44 1 2 1 3 2 4 3 5 4 6 2 7 4 8 1 9 3 10 1 11 8 12 2 13 9 14 1 15 1 16 15 17 15 18 7 19 1 20 19 21 13 22 10 23 17 24 9 25 9 26 24 27 8 28...
output:
180 168 222 230 156 240 225 126 100 81 155 73 154 127 149 124 228 230 132 187 153 170 78 282 195 286 191 211 119 197 211 233 88 252 239 233 173 180 195 121 109 148 180 175 226 210 182 97 199 59 56 31 115 204 203 172 139 208 53 140 189 170 173 137 233 94 163 273 80 350 156 133 146 159 240 269 137 222...
result:
ok 3000 numbers
Test #3:
score: 0
Accepted
time: 89ms
memory: 3860kb
input:
300 474 5 24 21 41 15 23 43 48 32 19 27 40 10 49 40 6 18 41 43 31 45 18 35 36 12 10 23 45 28 23 14 43 37 45 12 16 20 17 49 13 22 8 30 19 27 40 22 14 30 47 16 39 25 48 21 26 50 8 14 26 9 30 41 15 44 24 16 46 50 39 25 47 24 45 21 18 26 21 5 39 15 10 47 48 11 44 44 33 23 14 35 39 35 30 38 9 13 15 39 5 ...
output:
329 183 264 219 323 220 348 342 410 395 80 201 299 144 207 408 360 215 283 104 320 394 277 210 273 285 242 253 265 379 360 322 202 351 195 196 266 270 171 342 239 283 286 300 331 317 345 268 173 296 275 224 480 330 264 162 199 378 254 214 231 293 229 259 241 268 380 419 233 185 364 341 328 237 320 3...
result:
ok 300 numbers
Test #4:
score: 0
Accepted
time: 91ms
memory: 5092kb
input:
30 4926 18 13 47 7 21 39 28 48 21 44 14 18 39 13 46 33 6 49 9 7 10 29 29 25 38 15 16 42 41 41 40 14 26 13 6 19 17 31 24 18 30 24 48 46 38 21 28 42 29 50 33 28 18 26 18 42 13 23 35 20 32 6 17 25 44 46 35 36 50 24 7 29 34 14 41 41 8 33 22 46 7 6 22 40 24 8 44 36 38 13 37 37 25 22 7 43 50 33 19 44 24 4...
output:
427 520 443 359 427 408 371 415 482 436 269 530 478 485 435 453 418 503 443 453 405 425 347 564 297 435 559 453 213 395
result:
ok 30 numbers
Test #5:
score: 0
Accepted
time: 104ms
memory: 3592kb
input:
3000 74 555233197 518812085 998593787 821753058 967306600 663279435 696954042 885219300 489323226 146136486 447383587 785317885 838306349 708275482 715157265 298848995 400280904 374077023 673881523 207667786 885945020 459791675 992519779 327830583 821713695 253985403 926395863 419409783 138881726 80...
output:
6742611216 5794349776 3087356867 4707144715 2761702533 3246645261 4802134565 2999820393 4887036613 2784978973 3593730307 4783057633 4621084176 4331196830 4242984461 2287799528 3027767371 3699192818 3888960419 6398323452 2766114996 1734720583 6543430036 1955540148 5464479116 3177069662 5145942113 302...
result:
ok 3000 numbers
Test #6:
score: 0
Accepted
time: 93ms
memory: 3784kb
input:
300 621 259262308 372414267 976777900 567821544 262206094 972740633 932600104 702535786 494092920 919901107 797100568 708295156 632473907 101958470 952065075 970482879 183543308 323078517 719011818 352232578 159576652 124505381 125133768 492132730 331846050 577415810 369370004 871034176 529186574 44...
output:
8143086197 8197999468 5370721620 5343127707 5868323006 7992625789 5749423188 5019336842 5319894438 5228239187 5391752908 6084605805 6792215852 6057910407 8471127525 2719747215 6909535671 5100581420 5878004843 5586237425 6343902433 9390109727 5651124389 5472179570 7945151774 5064107530 4433748186 571...
result:
ok 300 numbers
Test #7:
score: 0
Accepted
time: 83ms
memory: 4836kb
input:
30 5308 560111855 290003681 946208440 140658046 860834453 480249720 506770353 922783074 600720525 693059141 436061359 545671168 528534807 339705109 831632761 570564203 113225613 578123930 293066534 269996029 765346927 443717770 933144287 856263710 475170893 174188152 464281143 864607591 443380284 12...
output:
8829755982 7996435040 9259425768 7684533044 9842457103 3917213508 5939555066 8695995697 9431906955 7466353560 8322921019 8970732656 8099619221 9390765699 6773331885 8521621715 9998520099 7876760589 6482847050 10167157889 8563826262 5569616375 7783052317 7313404561 7224267995 8986870714 9082031438 99...
result:
ok 30 numbers
Test #8:
score: 0
Accepted
time: 171ms
memory: 5788kb
input:
30 235 99 26 36 76 38 12 81 57 32 53 24 100 83 36 73 40 99 67 25 59 13 53 26 96 88 91 70 75 50 28 43 91 28 80 21 10 28 96 81 46 93 48 47 65 16 51 39 13 17 68 87 47 11 53 35 59 95 17 12 28 42 72 69 93 10 99 55 36 17 10 17 82 46 47 30 13 33 46 47 82 26 70 89 11 84 15 75 82 23 15 26 21 33 100 80 68 59 ...
output:
1853 53585 70793 41175 65095 19429 62735 44418 35618 52989 22194 74287 66783 60324 23354 10188 45849 43317 47709 44425 17639 2392 67454 75522 52049 63546 17778 37186 1857 31275
result:
ok 30 numbers
Test #9:
score: 0
Accepted
time: 295ms
memory: 23144kb
input:
3 99260 99 92 50 79 91 45 21 68 66 95 60 65 65 45 85 36 33 49 93 97 17 80 84 82 53 62 68 77 54 84 19 75 37 54 64 80 88 60 26 31 73 14 50 19 31 91 28 49 49 92 98 41 30 21 42 83 51 79 48 51 41 10 73 83 61 43 51 95 80 19 46 45 43 62 86 52 62 100 22 98 25 67 76 59 55 42 76 18 17 63 38 92 73 22 58 93 65 ...
output:
745947 689647 711794
result:
ok 3 number(s): "745947 689647 711794"
Test #10:
score: 0
Accepted
time: 210ms
memory: 20216kb
input:
3 100000 736164847 712451679 953221063 129734069 649878938 636159027 756625444 636178736 261073374 499660659 102302453 703591271 759851774 246224168 542866587 140617030 541228236 263272492 844843580 256780933 617601578 765332709 439622302 345560268 242255574 736020813 919249591 429525347 775345503 8...
output:
8765474998668 8767125090439 8759555000012
result:
ok 3 number(s): "8765474998668 8767125090439 8759555000012"
Test #11:
score: 0
Accepted
time: 186ms
memory: 5116kb
input:
30 10000 820875351 110118090 318290090 291550265 156728512 898695407 702936634 537529650 492026966 990954215 887311683 471855239 487268950 596796482 921910579 683211841 356504873 821436540 819581602 702676749 720024595 328497612 866905494 831557624 659171036 168505311 122782601 291094304 671588990 9...
output:
883467120694 893610662749 883906059936 882107337810 879231409121 884351970198 892461121041 888728631421 876218733693 882844635398 886784539966 883172718934 884651829402 884399545744 890807049327 887954375238 883852918523 888403782419 887498755532 880151218208 892907290650 882172390896 881732561237 8...
result:
ok 30 numbers
Test #12:
score: 0
Accepted
time: 229ms
memory: 16524kb
input:
3 100000 909474963 414166441 677161271 688542123 650201469 390309276 856663547 621207079 459811934 582838909 425785542 857661802 918712852 367645535 521783456 937759651 260632908 430905661 671167895 796755368 996221059 593819531 523770923 894242006 779434511 193459764 316358533 460721669 825011706 3...
output:
57147733548 44853213726 44403945508
result:
ok 3 number(s): "57147733548 44853213726 44403945508"
Test #13:
score: 0
Accepted
time: 211ms
memory: 16048kb
input:
3 100000 784731820 441612049 231013785 411550408 129294588 649753537 481462845 676592818 778982959 179403366 119330183 246561078 480033332 904236648 531363073 453276112 858901112 261361645 385753122 773663421 838636681 867032978 217985662 757527556 801360921 400949426 431795344 842282949 460946349 5...
output:
164667798192 128371764672 111980717406
result:
ok 3 number(s): "164667798192 128371764672 111980717406"
Test #14:
score: 0
Accepted
time: 148ms
memory: 16740kb
input:
3 100000 596147745 223984585 321060496 836040854 531932227 164460971 662224682 418129867 444375231 885587796 208707375 692215658 908699579 849426347 686769155 299416570 320642243 432987479 452056946 250651084 751940769 780605821 386414554 290323159 222811216 656912068 831464659 621638040 952600162 9...
output:
435962040433 558704468744 578552805560
result:
ok 3 number(s): "435962040433 558704468744 578552805560"
Test #15:
score: 0
Accepted
time: 198ms
memory: 3724kb
input:
300 1000 306155973 502827111 154815976 498580847 143323927 427577658 729017009 385469320 282879354 730478149 292829273 716249730 785070076 560330250 598364372 939399616 585039212 850280897 722508936 220628755 135815134 579721227 353260095 293228175 586309693 503298178 847459502 536849421 625285745 6...
output:
10262465475 19119326129 12062920235 12137743449 13594380675 17341639220 10991714214 18829859456 17577744690 14603342312 17177860522 19397559314 22251073639 13630162409 15953666923 23921433778 23214301266 24629614692 13126058238 26897894988 10714431253 15557242432 18578687240 13481669075 18359475028 ...
result:
ok 300 numbers
Test #16:
score: 0
Accepted
time: 117ms
memory: 40688kb
input:
3 100000 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 114514 1145...
output:
229028 229028 229028
result:
ok 3 number(s): "229028 229028 229028"