#include "joitour.h"
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <vector>
using namespace std;
using ll = long long;
using db = long double; // or double, if TL is tight
using str = string; // yay python!
// pairs
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<db, db>;
#define mp make_pair
#define f first
#define s second
#define tcT template <class T
#define tcTU tcT, class U
// ^ lol this makes everything look weird but I'll try it
tcT > using V = vector<T>;
tcT, size_t SZ > using AR = array<T, SZ>;
using vi = V<int>;
using vb = V<bool>;
using vl = V<ll>;
using vd = V<db>;
using vs = V<str>;
using vpi = V<pi>;
using vpl = V<pl>;
using vpd = V<pd>;
// vectors
#define sz(x) int(size(x))
#define bg(x) begin(x)
#define all(x) bg(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define pb push_back
#define eb emplace_back
#define ft front()
#define bk back()
#define lb lower_bound
#define ub upper_bound
tcT > int lwb(const V<T> &a, const T &b) { return int(lb(all(a), b) - bg(a)); }
tcT > int upb(const V<T> &a, const T &b) { return int(ub(all(a), b) - bg(a)); }
// loops
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define F0R(i, a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i, a) ROF(i, 0, a)
#define rep(a) F0R(_, a)
#define each(a, x) for (auto &a : x)
const int MOD = 998244353; // 1e9+7;
const int MX = (int)2e5 + 5;
const ll BIG = 1e18; // not too close to LLONG_MAX
const db PI = acos((db)-1);
const int dx[4]{1, 0, -1, 0}, dy[4]{0, 1, 0, -1}; // for every grid problem!!
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
// bitwise ops
// also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(
int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...
return x == 0 ? 0 : 31 - __builtin_clz(x);
} // floor(log2(x))
constexpr int p2(int x) { return 1 << x; }
constexpr int msk2(int x) { return p2(x) - 1; }
ll cdiv(ll a, ll b) {
return a / b + ((a ^ b) > 0 && a % b);
} // divide a by b rounded up
ll fdiv(ll a, ll b) {
return a / b - ((a ^ b) < 0 && a % b);
} // divide a by b rounded down
tcT > bool ckmin(T &a, const T &b) {
return b < a ? a = b, 1 : 0;
} // set a = min(a,b)
tcT > bool ckmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
} // set a = max(a,b)
tcTU > T fstTrue(T lo, T hi, U f) {
++hi;
assert(lo <= hi); // assuming f is increasing
while (lo < hi) { // find first index such that f is true
T mid = lo + (hi - lo) / 2;
f(mid) ? hi = mid : lo = mid + 1;
}
return lo;
}
tcTU > T lstTrue(T lo, T hi, U f) {
--lo;
assert(lo <= hi); // assuming f is decreasing
while (lo < hi) { // find first index such that f is true
T mid = lo + (hi - lo + 1) / 2;
f(mid) ? lo = mid : hi = mid - 1;
}
return lo;
}
tcT > void remDup(vector<T> &v) { // sort and remove duplicates
sort(all(v));
v.erase(unique(all(v)), end(v));
}
tcTU > void safeErase(T &t, const U &u) {
auto it = t.find(u);
assert(it != end(t));
t.erase(it);
}
inline namespace IO {
#define SFINAE(x, ...) \
template <class, class = void> struct x : std::false_type {}; \
template <class T> struct x<T, std::void_t<__VA_ARGS__>> : std::true_type {}
SFINAE(DefaultI, decltype(std::cin >> std::declval<T &>()));
SFINAE(DefaultO, decltype(std::cout << std::declval<T &>()));
SFINAE(IsTuple, typename std::tuple_size<T>::type);
SFINAE(Iterable, decltype(std::begin(std::declval<T>())));
template <auto &is> struct Reader {
template <class T> void Impl(T &t) {
if constexpr (DefaultI<T>::value)
is >> t;
else if constexpr (Iterable<T>::value) {
for (auto &x : t)
Impl(x);
} else if constexpr (IsTuple<T>::value) {
std::apply([this](auto &...args) { (Impl(args), ...); }, t);
} else
static_assert(IsTuple<T>::value, "No matching type for read");
}
template <class... Ts> void read(Ts &...ts) { ((Impl(ts)), ...); }
};
template <class... Ts> void re(Ts &...ts) { Reader<cin>{}.read(ts...); }
#define def(t, args...) \
t args; \
re(args);
template <auto &os, bool debug, bool print_nd> struct Writer {
string comma() const { return debug ? "," : ""; }
template <class T> constexpr char Space(const T &) const {
return print_nd && (Iterable<T>::value or IsTuple<T>::value) ? '\n' : ' ';
}
template <class T> void Impl(T const &t) const {
if constexpr (DefaultO<T>::value)
os << t;
else if constexpr (Iterable<T>::value) {
if (debug)
os << '{';
int i = 0;
for (auto &&x : t)
((i++) ? (os << comma() << Space(x), Impl(x)) : Impl(x));
if (debug)
os << '}';
} else if constexpr (IsTuple<T>::value) {
if (debug)
os << '(';
std::apply(
[this](auto const &...args) {
int i = 0;
(((i++) ? (os << comma() << " ", Impl(args)) : Impl(args)), ...);
},
t);
if (debug)
os << ')';
} else
static_assert(IsTuple<T>::value, "No matching type for print");
}
template <class T> void ImplWrapper(T const &t) const {
if (debug)
os << "\033[0;31m";
Impl(t);
if (debug)
os << "\033[0m";
}
template <class... Ts> void print(Ts const &...ts) const {
((Impl(ts)), ...);
}
template <class F, class... Ts>
void print_with_sep(const std::string &sep, F const &f,
Ts const &...ts) const {
ImplWrapper(f), ((os << sep, ImplWrapper(ts)), ...), os << '\n';
}
void print_with_sep(const std::string &) const { os << '\n'; }
};
template <class... Ts> void pr(Ts const &...ts) {
Writer<cout, false, true>{}.print(ts...);
}
template <class... Ts> void ps(Ts const &...ts) {
Writer<cout, false, true>{}.print_with_sep(" ", ts...);
}
} // namespace IO
inline namespace Debug {
template <typename... Args> void err(Args... args) {
Writer<cerr, true, false>{}.print_with_sep(" | ", args...);
}
template <typename... Args> void errn(Args... args) {
Writer<cerr, true, true>{}.print_with_sep(" | ", args...);
}
void err_prefix(str func, int line, string args) {
cerr << "\033[0;31m\u001b[1mDEBUG\033[0m"
<< " | "
<< "\u001b[34m" << func << "\033[0m"
<< ":"
<< "\u001b[34m" << line << "\033[0m"
<< " - "
<< "[" << args << "] = ";
}
#ifdef LOCAL
#define dbg(args...) err_prefix(__FUNCTION__, __LINE__, #args), err(args)
#define dbgn(args...) err_prefix(__FUNCTION__, __LINE__, #args), errn(args)
#else
#define dbg(...)
#define dbgn(args...)
#endif
const auto beg_time = std::chrono::high_resolution_clock::now();
// https://stackoverflow.com/questions/47980498/accurate-c-c-clock-on-a-multi-core-processor-with-auto-overclock?noredirect=1&lq=1
double time_elapsed() {
return chrono::duration<double>(std::chrono::high_resolution_clock::now() -
beg_time)
.count();
}
} // namespace Debug
inline namespace FileIO {
void setIn(str s) { freopen(s.c_str(), "r", stdin); }
void setOut(str s) { freopen(s.c_str(), "w", stdout); }
void setIO(str s = "") {
cin.tie(0)->sync_with_stdio(0); // unsync C / C++ I/O streams
cout << fixed << setprecision(12);
// cin.exceptions(cin.failbit);
// throws exception when do smth illegal
// ex. try to read letter into int
if (sz(s))
setIn(s + ".in"), setOut(s + ".out"); // for old USACO
}
} // namespace FileIO
enum Type { Vertex, Compress, Rake, AddEdge, AddVertex };
// g must be a rooted tree
struct StaticTopTree {
vector<vector<int>> &g;
int root; // an index of the root in g
int stt_root; // an index of the root in static top tree
vector<int> P, L, R; // parent, left child, right child
vector<Type> T; // type of vertices
int add_buf; // a variable for the member function
StaticTopTree(vector<vector<int>> &_g, int _root = 0) : g(_g), root(_root) {
int n = g.size();
P.resize(4 * n, -1), L.resize(4 * n, -1), R.resize(4 * n, -1);
T.resize(4 * n, Type::Vertex);
add_buf = n;
build();
}
private:
int dfs(int c) {
int s = 1, best = 0;
for (int &d : g[c]) {
int t = dfs(d);
s += t;
if (best < t)
best = t, swap(d, g[c][0]);
}
return s;
}
int add(int k, int l, int r, Type t) {
if (k == -1)
k = add_buf++;
P[k] = -1, L[k] = l, R[k] = r, T[k] = t;
if (l != -1)
P[l] = k;
if (r != -1)
P[r] = k;
return k;
}
pair<int, int> merge(const vector<pair<int, int>> &a, Type t) {
if (a.size() == 1)
return a[0];
int u = 0;
for (auto &[_, s] : a)
u += s;
vector<pair<int, int>> b, c;
for (auto &[i, s] : a)
(u > s ? b : c).emplace_back(i, s), u -= s * 2;
auto [i, si] = merge(b, t);
auto [j, sj] = merge(c, t);
return {add(-1, i, j, t), si + sj};
}
pair<int, int> compress(int i) {
vector<pair<int, int>> chs{add_vertex(i)};
while (!g[i].empty())
chs.push_back(add_vertex(i = g[i][0]));
return merge(chs, Type::Compress);
}
pair<int, int> rake(int i) {
vector<pair<int, int>> chs;
for (int j = 1; j < (int)g[i].size(); j++)
chs.push_back(add_edge(g[i][j]));
return chs.empty() ? make_pair(-1, 0) : merge(chs, Type::Rake);
}
pair<int, int> add_edge(int i) {
auto [j, sj] = compress(i);
return {add(-1, j, -1, Type::AddEdge), sj};
}
pair<int, int> add_vertex(int i) {
auto [j, sj] = rake(i);
return {add(i, j, -1, j == -1 ? Type::Vertex : Type::AddVertex), sj + 1};
}
void build() {
dfs(root);
auto [i, n] = compress(root);
stt_root = i;
}
};
// #include "atcoder/modint.hpp"
// using mint = atcoder::modint998244353;
// vector<int> A;
struct Path {
ll J, I, JO, IO, JOI;
ll J_path, O_path, I_path;
ll JO_path, OJ_path, IO_path, OI_path;
};
struct Point {
ll J, I, JO, IO, JOI, JI;
};
vi type;
Path vertex(int v) {
Path ret{};
if (type.at(v) == 0)
++ret.J, ++ret.J_path;
else if (type.at(v) == 1)
++ret.O_path;
else {
assert(type.at(v) == 2);
++ret.I, ++ret.I_path;
}
return ret;
}
Path compress(Path p, Path c) {
return {
c.J + p.J,
c.I + p.I,
c.JO + p.JO + c.J * p.O_path,
c.IO + p.IO + c.I * p.O_path,
c.JOI + p.JOI + c.J * (p.IO - p.IO_path + p.OI_path) + c.JO * p.I +
c.I * (p.JO - p.JO_path + p.OJ_path) + c.IO * p.J, // JOI, IOJ
c.J_path + p.J_path,
c.O_path + p.O_path,
c.I_path + p.I_path,
c.JO_path + p.JO_path + c.J_path * p.O_path,
c.OJ_path + p.OJ_path + c.O_path * p.J_path,
c.IO_path + p.IO_path + c.I_path * p.O_path,
c.OI_path + p.OI_path + c.O_path * p.I_path,
};
}
Path add_vertex(Point t, int v) {
return Path{
t.J + (type.at(v) == 0),
t.I + (type.at(v) == 2),
t.JO + t.J * (type.at(v) == 1),
t.IO + t.I * (type.at(v) == 1),
t.JOI + t.IO * (type.at(v) == 0) + t.JO * (type.at(v) == 2) +
t.JI * (type.at(v) == 1),
(type.at(v) == 0),
(type.at(v) == 1),
(type.at(v) == 2),
0,
0,
0,
0,
};
}
Point rake(Point x, Point y) {
return {x.J + y.J,
x.I + y.I,
x.JO + y.JO,
x.IO + y.IO,
x.JOI + y.JOI + x.J * y.IO + x.JO * y.I + x.I * y.JO + x.IO * y.J,
x.JI + y.JI + x.J * y.I + x.I * y.J};
}
// J, O, I, JO, OI, JOI
Point add_edge(Path t) { return {t.J, t.I, t.JO, t.IO, t.JOI}; }
// https://atcoder.jp/contests/abc351/tasks/abc351_g
/**
* Description: wraps a lambda so it can call itself
* Source: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0200r0.html
*/
namespace std {
template <class Fun> class y_combinator_result {
Fun fun_;
public:
template <class T>
explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)) {}
template <class... Args> decltype(auto) operator()(Args &&...args) {
return fun_(std::ref(*this), std::forward<Args>(args)...);
}
};
template <class Fun> decltype(auto) y_combinator(Fun &&fun) {
return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}
} // namespace std
void y_comb_demo() {
cout << y_combinator([](auto gcd, int a, int b) -> int {
return b == 0 ? a : gcd(b, a % b);
})(20, 30)
<< "\n"; // outputs 10
}
struct SttWrapper {
StaticTopTree stt;
vector<Path> path;
vector<Point> point;
SttWrapper(V<vi> g) : stt(g), path(stt.L.size()), point(stt.L.size()) {
auto dfs = [&](auto rc, int k) -> void {
if (stt.L[k] != -1)
rc(rc, stt.L[k]);
if (stt.R[k] != -1)
rc(rc, stt.R[k]);
update(k);
};
dfs(dfs, stt.stt_root);
}
void update(int k) {
if (stt.T[k] == Type::Vertex) {
path[k] = vertex(k);
} else if (stt.T[k] == Type::Compress) {
path[k] = compress(path[stt.L[k]], path[stt.R[k]]);
} else if (stt.T[k] == Type::Rake) {
point[k] = rake(point[stt.L[k]], point[stt.R[k]]);
} else if (stt.T[k] == Type::AddEdge) {
point[k] = add_edge(path[stt.L[k]]);
} else {
path[k] = add_vertex(point[stt.L[k]], k);
}
}
void change(int v, int Y) {
type.at(v) = Y;
while (v != -1)
update(v), v = stt.P[v];
}
ll query() { return path[stt.stt_root].JOI; }
};
SttWrapper *stt;
void init(int N, std::vector<int> F, std::vector<int> U, std::vector<int> V,
int Q) {
type = F;
vector<vector<int>> adj(N);
F0R(i, N - 1) adj.at(U.at(i)).pb(V.at(i)), adj.at(V.at(i)).pb(U.at(i));
vector<vector<int>> g(N);
y_combinator([&](auto dfs, int u, int p) -> void {
for (int v : adj.at(u))
if (v != p) {
g.at(u).pb(v);
dfs(v, u);
}
})(0, -1);
stt = new SttWrapper(g);
}
void change(int v, int Y) { stt->change(v, Y); }
long long num_tours() { return stt->query(); }
Compilation message (stderr)
joitour.cpp: In function 'void FileIO::setIn(str)':
joitour.cpp:257:28: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
257 | void setIn(str s) { freopen(s.c_str(), "r", stdin); }
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
joitour.cpp: In function 'void FileIO::setOut(str)':
joitour.cpp:258:29: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
258 | void setOut(str s) { freopen(s.c_str(), "w", stdout); }
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |