#include <bits/stdc++.h>
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
#ifdef LOCAL
template<typename A, typename B>
auto&operator<<(auto&o,pair<A, B>p){return o<<"("<<p.first<<", "<<p.second<<")";}
auto operator<<(auto&o,auto x)->decltype(x.end(),o){o<<"{";int i=0;for(auto e:x)o<<&","[!i++]<<e;return o<<"}";}
#define debug(X...)cerr<<"["#X"]: ",[](auto...$){((cerr<<$<<"; "),...)<<endl;}(X)
#else
#define debug(...){}
#endif
using i64 = long long;
using ll = long long;
#define int i64
using pii = pair<int, int>;
using pll = pair<i64, i64>;
using vi = vector<int>;
using vll = vector<i64>;
const i64 INF = 2e18;
template <typename Tp>
void maxi(Tp &a, Tp b) { a = max(a, b); }
int T = 1;
struct MajorizationContainer {
MajorizationContainer() {}
vector<pll> items;
void AddPair(i64 a, i64 b) {
items.emplace_back(a, b);
}
void Process() {
sort(ALL(items));
vector<pll> res;
for (const auto [a, b] : items) {
while (!res.empty() && res.back().first <= a && res.back().second <= b) {
res.pop_back();
}
res.emplace_back(a, b);
}
swap(items, res);
}
bool IsMajorized(i64 a, i64 b) const {
pll cand{a, b};
const auto iter = lower_bound(ALL(items), cand);
if (iter == items.end()) {
return false;
}
return (iter->first >= a && iter->second >= b);
}
};
struct UnsortedLBSearcher {
int base;
vll data;
UnsortedLBSearcher() {}
UnsortedLBSearcher(const vll &items) {
const int n = SZ(items);
base = 1;
while (base < n + 5) { base *= 2; }
data.resize(base * 2, -INF);
for (int i = 0; i < n; ++i) {
data[i + base] = items[i];
}
data[n + base] = INF;
for (int i = base - 1; i > 0; --i) {
data[i] = max(data[i * 2], data[i * 2 + 1]);
}
}
int FirstGeqOnSuffix(int start, i64 x) const {
int v = start + base;
while (data[v] < x) {
if (v % 2 == 1) { ++v; }
v /= 2;
assert(v);
}
while (v < base) {
if (data[v * 2] >= x) {
v *= 2;
} else {
v = v * 2 + 1;
}
assert(data[v] >= x);
}
return v - base;
}
};
struct APlusBSearcher {
int base;
struct Node {
i64 max_a = -INF, max_b = -INF, max_aplusb = -INF;
const Node Merge(const Node &rhs) const {
Node ans;
ans.max_a = max(max_a, rhs.max_a);
ans.max_b = max(max_b, rhs.max_b);
ans.max_aplusb = max({max_aplusb, rhs.max_aplusb, max_a + rhs.max_b});
return ans;
}
};
vector<Node> data;
APlusBSearcher() {}
APlusBSearcher(const vll &A, const vll &B) {
debug("APlusBSearcher", A, B);
const int n = SZ(A);
base = 1;
while (base < n + 5) { base *= 2; }
data.resize(base * 2);
for (int i = 0; i < n; ++i) {
data[i + base].max_a = A[i];
data[i + base].max_b = B[i];
}
data[n + base].max_aplusb = INF;
for (int i = base - 1; i > 0; --i) {
data[i] = data[i * 2].Merge(data[i * 2 + 1]);
}
}
int FirstStopWithAPlusBGeqX(int start, i64 x) const {
debug("APlusBSearch-Query", start, x);
Node cur_pref;
int v = start + base;
while (cur_pref.Merge(data[v]).max_aplusb < x) {
if (v % 2 == 1) {
cur_pref = cur_pref.Merge(data[v]);
++v;
}
v /= 2;
assert(v);
}
debug(base, v);
while (v < base) {
const Node &cand_pref = cur_pref.Merge(data[v * 2]);
if (cand_pref.max_aplusb >= x) {
v *= 2;
} else {
cur_pref = cand_pref;
v = v * 2 + 1;
}
assert(cur_pref.Merge(data[v]).max_aplusb >= x);
}
const int ans = v - base;
debug(ans);
return v - base;
}
};
struct Testcase {
int n, q, sz;
struct Edge {
int to;
i64 cost;
};
vector<vector<Edge>> graph;
vll parent;
vll diameter;
vll diameter_pos;
vll dist_to_diameter;
vll diameter_repr;
vll depth;
vll longest_rooted_path_dn;
vll longest_inside_path_dn;
vll longest_outside_path_dn;
vll longest_rooted_path_up;
MajorizationContainer path_pairs_all, path_pairs_nodiag;
vector<MajorizationContainer> cloned_subtree_pairs;
ll best_nodiag;
void AddEdge(int u, int v, i64 c) {
// debug(u, v, c);
graph[u].push_back({.to = v, .cost = c});
graph[v].push_back({.to = u, .cost = c});
}
void Input() {
cin >> n;
if (n < 0) { // FUNNY HACK
assert(T == 1);
T = -n;
cin >> n;
}
cin >> q;
graph.resize(n + 1);
for (int i = 0; i < n - 1; ++i) {
int u, v;
i64 c;
cin >> u >> v >> c;
AddEdge(u, v, c);
}
}
int FindFarthest(int v) {
function<pair<int, i64>(int, int)> Dfs = [&](int v, int p) {
pair<int, i64> ans{v, 0};
for (const auto &edge : graph[v]) {
if (edge.to == p) { continue; }
auto [s, d] = Dfs(edge.to, v);
d += edge.cost;
if (d > ans.second) {
ans = {s, d};
}
}
return ans;
};
return Dfs(v, -1).first;
}
vll FindPath(int a, int b) {
vll ans;
function<bool(int, int)> Dfs = [&](int v, int p) {
if (v == a) {
ans.push_back(a);
return true;
}
for (const auto &edge : graph[v]) {
if (edge.to == p) { continue; }
if (Dfs(edge.to, v)) {
ans.push_back(v);
return true;
}
}
return false;
};
const bool ret = Dfs(b, -1);
assert(ret);
return ans;
}
void DfsBasicDiameterDepth(int v, int p) {
for (const auto &edge : graph[v]) {
if (edge.to == p) { continue; }
depth[edge.to] = depth[v] + edge.cost;
if (diameter_pos[edge.to] == -1) {
diameter_repr[edge.to] = diameter_repr[v];
dist_to_diameter[edge.to] = dist_to_diameter[v] + edge.cost;
}
DfsBasicDiameterDepth(edge.to, v);
}
}
void CloneSubtree(int diameter_vtx, int branch, i64 first_cost) {
function<void(int, int)> Dfs = [&](int v, int p) {
for (const auto &edge : graph[v]) {
const int s = edge.to;
if (s == p) { continue; }
const int nv = v + n;
const int ns = s + n;
AddEdge(nv, ns, edge.cost);
depth[ns] = depth[nv] + edge.cost;
Dfs(s, v);
}
};
const int nr = branch + n;
const int nd = nr + n;
debug("Clone", nd, nr, first_cost);
AddEdge(nd, nr, first_cost);
depth[nd] = 0;
depth[nr] = first_cost;
Dfs(branch, diameter_vtx);
}
void FindAndProcessDiameter() {
const int diam_end1 = FindFarthest(1);
const int diam_end2 = FindFarthest(diam_end1);
diameter = FindPath(diam_end1, diam_end2);
debug(diameter);
diameter_pos.resize(n + 1, -1);
diameter_repr.resize(n + 1, -1);
for (int i = 0; i < SZ(diameter); ++i) {
diameter_pos[diameter[i]] = i;
diameter_repr[diameter[i]] = diameter[i];
}
dist_to_diameter.resize(n + 1);
depth.resize(n + 1);
DfsBasicDiameterDepth(diam_end1, -1);
debug(diameter_pos);
debug(diameter_repr);
debug(dist_to_diameter);
debug(depth);
graph.resize(3 * n + 1);
parent.resize(3 * n + 1);
depth.resize(3 * n + 1);
sz = 3 * n;
for (int v : diameter) {
for (const auto &edge : graph[v]) {
const int s = edge.to;
if (diameter_pos[s] != -1) { continue; }
CloneSubtree(v, s, edge.cost);
}
}
}
void FindLongSubtreePaths() {
longest_inside_path_dn.resize(sz + 1, -1);
longest_outside_path_dn.resize(sz + 1, -1);
longest_rooted_path_dn.resize(sz + 1, -1);
longest_rooted_path_up.resize(sz + 1, -1);
vector<vll> rooted_cand_lists(sz + 1);
vector<vll> inside_cand_lists(sz + 1);
function<void(int, int)> DfsDn = [&](int v, int p) {
parent[v] = p;
longest_rooted_path_dn[v] = longest_inside_path_dn[v] = 0;
for (const auto &edge : graph[v]) {
if (edge.to == p) { continue; }
const int s = edge.to;
DfsDn(s, v);
const i64 cand = longest_rooted_path_dn[s] + edge.cost;
maxi(longest_rooted_path_dn[v], cand);
maxi(longest_inside_path_dn[v], longest_inside_path_dn[s]);
rooted_cand_lists[v].push_back(cand);
inside_cand_lists[v].push_back(longest_inside_path_dn[s]);
}
sort(ALL(rooted_cand_lists[v]), greater<i64>());
sort(ALL(inside_cand_lists[v]), greater<i64>());
if (!rooted_cand_lists[v].empty()) {
maxi(longest_inside_path_dn[v], rooted_cand_lists[v][0]);
}
if (SZ(rooted_cand_lists[v]) >= 2) {
maxi(longest_inside_path_dn[v], rooted_cand_lists[v][0] + rooted_cand_lists[v][1]);
}
debug(v, longest_rooted_path_dn[v], rooted_cand_lists[v], longest_inside_path_dn[v]);
};
function<void(int, int, i64)> DfsUp = [&](int v, int p, i64 cur_up_rooted) {
debug(v, p, cur_up_rooted, longest_outside_path_dn[v]);
longest_rooted_path_up[v] = cur_up_rooted;
if (p != -1) {
rooted_cand_lists[v].push_back(cur_up_rooted);
sort(ALL(rooted_cand_lists[v]), greater<i64>());
}
debug(inside_cand_lists[v]);
for (const auto &edge : graph[v]) {
if (edge.to == p) { continue; }
const int s = edge.to;
maxi(longest_outside_path_dn[s], longest_outside_path_dn[v]);
if (inside_cand_lists[v][0] != longest_inside_path_dn[s]) {
maxi(longest_outside_path_dn[s], inside_cand_lists[v][0]);
} else if (SZ(inside_cand_lists[v]) >= 2) {
maxi(longest_outside_path_dn[s], inside_cand_lists[v][1]);
}
i64 next_up_rooted = 0;
i64 outside_cand = 0;
int num_used = 0;
bool is_skipped = false;
const i64 skip_cand = longest_rooted_path_dn[s] + edge.cost;
for (i64 cand : rooted_cand_lists[v]) {
if (cand == skip_cand && !is_skipped) {
is_skipped = true;
} else {
if (num_used == 0) { next_up_rooted = cand; }
outside_cand += cand;
++num_used;
if (num_used == 2) { break; }
}
}
maxi(longest_outside_path_dn[s], outside_cand);
DfsUp(s, v, next_up_rooted + edge.cost);
}
};
DfsDn(diameter[0], -1);
DfsUp(diameter[0], -1, 0);
for (int i = 2 * n + 1; i <= 3 * n; ++i) {
DfsDn(i, -1);
DfsUp(i, -1, 0);
}
}
void PreprocOneAndTwoPathCases() {
auto AddCand = [&](MajorizationContainer &dest, i64 a, i64 b) {
if (a < b) { swap(a, b); }
dest.AddPair(a, b);
};
auto AddCandForEdge = [&](MajorizationContainer &dest, int v) {
const int pnt = parent[v];
const i64 edge_len = depth[v] - depth[pnt];
AddCand(dest, longest_inside_path_dn[v], longest_outside_path_dn[v]);
AddCand(dest, longest_rooted_path_dn[v] + edge_len, longest_outside_path_dn[v]);
AddCand(dest, longest_inside_path_dn[v], longest_rooted_path_up[v]);
};
for (int v = 1; v <= n; ++v) {
if (v != diameter[0]) {
AddCandForEdge(path_pairs_all, v);
}
}
path_pairs_all.Process();
debug(path_pairs_all.items);
best_nodiag = 0;
vll single_paths(2);
for (int v = 2 * n + 1; v <= 3 * n; ++v) {
single_paths.push_back(longest_inside_path_dn[v]);
}
for (int v = 1; v <= n; ++v) {
if (diameter_pos[v] == -1) {
AddCandForEdge(path_pairs_nodiag, v + n);
}
}
sort(ALL(single_paths), greater<i64>());
best_nodiag = single_paths[0];
path_pairs_nodiag.AddPair(single_paths[0], single_paths[1]);
path_pairs_nodiag.Process();
debug(path_pairs_nodiag.items);
debug(best_nodiag);
}
bool ContainsPathPair(i64 L1, i64 L2, MajorizationContainer &search_target) {
if (L1 < L2) { swap(L1, L2); }
return search_target.IsMajorized(L1, L2);
}
vll search_vertex_start;
vll search_vertex_end;
vll search_ends;
vll search_depth;
vll search_addlen;
vll search_vtx;
struct SearchInsidePaths {
int idx;
int vtx_i;
i64 fit_size;
bool operator<(const SearchInsidePaths &other) const {
return fit_size < other.fit_size;
}
bool operator>(const SearchInsidePaths &other) const {
return fit_size > other.fit_size;
}
};
vector<SearchInsidePaths> search_inside_paths;
UnsortedLBSearcher search_prefix_inside_lb;
UnsortedLBSearcher search_suffix_inside_lb;
APlusBSearcher search_aplusb;
void PreprocDiameterForSearches() {
search_vertex_start.resize(n + 1, -1);
search_vertex_end.resize(n + 1, -1);
auto InjectInfo = [&](i64 diam_repr, i64 v, i64 rooted_len) {
const i64 idx = SZ(search_vtx);
search_vtx.push_back(v);
search_depth.push_back(depth[diam_repr]);
search_addlen.push_back(rooted_len);
return idx;
};
for (int v : diameter) {
search_vertex_start[v] = InjectInfo(v, v, 0);
search_ends.push_back(search_vertex_start[v]);
for (const auto &edge : graph[v]) {
const int s = edge.to;
if (diameter_pos[edge.to] != -1) { continue; }
InjectInfo(v, s, longest_rooted_path_dn[s + 2 * n]);
}
search_vertex_end[v] = InjectInfo(v, v, 0);
search_ends.push_back(search_vertex_end[v]);
}
for (int i = 0; i < SZ(search_vtx); ++i) {
debug(i, search_vtx[i], search_depth[i], search_addlen[i]);
}
cloned_subtree_pairs.resize(3 * n + 1);
int cur_cloned_root = -1;
function<void(int, i64)> DfsRootedAndOther = [&](int v, i64 best_other) {
cloned_subtree_pairs[cur_cloned_root].AddPair(
depth[v], max(best_other, longest_inside_path_dn[v]));
vll cands_inside{0};
vll cands_rooted{0};
for (const auto &edge : graph[v]) {
if (edge.to == parent[v]) { continue; }
cands_inside.push_back(longest_inside_path_dn[edge.to]);
cands_rooted.push_back(longest_rooted_path_dn[edge.to] + edge.cost);
}
sort(ALL(cands_inside), greater<i64>());
sort(ALL(cands_rooted), greater<i64>());
for (const auto &edge : graph[v]) {
if (edge.to == parent[v]) { continue; }
i64 inside_cand = cands_inside[0];
if (inside_cand == longest_inside_path_dn[edge.to]) {
inside_cand = cands_inside[1];
}
i64 rooted_cand = cands_rooted[0];
const i64 rooted_chk = longest_rooted_path_dn[edge.to] + edge.cost;
if (rooted_cand == rooted_chk) {
rooted_cand = cands_rooted[1];
}
const i64 next_other = max({best_other, inside_cand, rooted_cand});
DfsRootedAndOther(edge.to, next_other);
}
};
for (int v = 2 * n + 1; v <= 3 * n; ++v) {
cur_cloned_root = v;
DfsRootedAndOther(v, 0);
cloned_subtree_pairs[v].Process();
debug(v, cloned_subtree_pairs[v].items);
}
for (int i = 0; i < SZ(search_vtx); ++i) {
const int vtx_i = search_vtx[i];
const int repr_i = diameter_repr[vtx_i];
if (vtx_i == repr_i) { continue; }
const i64 fit_size = longest_inside_path_dn[vtx_i + 2 * n];
search_inside_paths.push_back({.idx = i, .vtx_i = vtx_i, .fit_size = fit_size});
}
sort(ALL(search_inside_paths), greater<SearchInsidePaths>());
if (SZ(search_inside_paths) > 3) {
search_inside_paths.resize(3);
}
vll data_prefix_inside, data_suffix_inside;
for (int i = 0; i < SZ(search_vtx); ++i) {
data_prefix_inside.push_back(search_depth[i] + search_addlen[i]);
}
for (int i = SZ(search_vtx) - 1; i >= 0; --i) {
data_suffix_inside.push_back((search_depth.back() - search_depth[i]) + search_addlen[i]);
}
search_prefix_inside_lb = UnsortedLBSearcher{data_prefix_inside};
search_suffix_inside_lb = UnsortedLBSearcher{data_suffix_inside};
vll aplusb_data_A, aplusb_data_B;
for (int i = 0; i < SZ(search_vtx); ++i) {
aplusb_data_A.push_back(search_addlen[i] - search_depth[i]);
aplusb_data_B.push_back(search_depth[i] + search_addlen[i]);
}
search_aplusb = APlusBSearcher(aplusb_data_A, aplusb_data_B);
}
i64 SearchRoundToEnd(i64 R) {
if (R >= SZ(search_vtx)) {
return SZ(search_vtx);
}
R = *lower_bound(ALL(search_ends), R);
return R;
}
int FindFirstOnDiameterOfLength(int start, i64 len) {
const int ans_fast = search_aplusb.FirstStopWithAPlusBGeqX(start, len);
// const int ans_slow = FindFirstOnDiameterOfLengthSlow(start, len);
// debug(ans_fast, ans_slow);
// assert(ans_fast == ans_slow);
return ans_fast;
}
bool FitsRootedPathAndOtherPath(int root, i64 len_rooted, i64 len_other) {
return cloned_subtree_pairs[root].IsMajorized(len_rooted, len_other);
}
bool SolveQuery(vll lengths) {
sort(ALL(lengths), greater<i64>());
// Yes-Case 1: all inside the diameter
const i64 diam_length = depth[diameter.back()];
if (lengths[0] + lengths[1] + lengths[2] <= diam_length) {
debug("Yes-Case 1");
return true;
}
// No-Case 1: lengths[0] doesn't fit the diameter
if (lengths[0] > diam_length) {
debug("No-Case 1");
return false;
}
// Yes-Case 2: longest inside the diameter, two other outside the diameter
if (ContainsPathPair(lengths[1], lengths[2], path_pairs_nodiag)) {
debug("Yes-Case 2");
return true;
}
// Yes-Case 3: There is some path coupling that works
for (int outsider : {0, 1, 2}) {
const i64 path_a = lengths[0] + lengths[1] + lengths[2] - lengths[outsider];
const i64 path_b = lengths[outsider];
if (ContainsPathPair(path_a, path_b, path_pairs_all)) {
debug("Yes-Case 3", outsider, path_a, path_b);
return true;
}
}
// Yes-Case 4: All three paths intersect the diameter non-trivially
// (i.e., containing internally some point of the diameter)
{
vll intersect_order = lengths;
sort(ALL(intersect_order));
do {
i64 loc = 0;
for (i64 len : intersect_order) {
loc = SearchRoundToEnd(loc);
loc = FindFirstOnDiameterOfLength(loc, len);
// debug(intersect_order, len, loc);
}
if (loc < SZ(search_vtx)) {
debug("Yes-Case 4", intersect_order);
return true;
}
} while (next_permutation(ALL(intersect_order)));
}
// Yes-Case 5: One path has the start of the diameter, second has the end of the diameter,
// the third does not touch the diameter (non-trivially)
vll path_order = lengths;
sort(ALL(path_order));
auto CheckPathOrder = [&]() {
const i64 len_pref = path_order[0];
const i64 len_suf = path_order[1];
const i64 len_inside = path_order[2];
vector<int> Ls, Rs;
{
int cur = 0;
for (int i = 0; i < 2 && cur < SZ(search_vtx); ++i) {
const int nxt = search_prefix_inside_lb.FirstGeqOnSuffix(cur, len_pref);
if (nxt >= SZ(search_vtx)) { break; }
Ls.push_back(nxt);
cur = nxt + 1;
}
}
{
int cur = 0;
for (int i = 0; i < 2 && cur < SZ(search_vtx); ++i) {
const int nxt = search_suffix_inside_lb.FirstGeqOnSuffix(cur, len_suf);
if (nxt >= SZ(search_vtx)) { break; }
Rs.push_back(SZ(search_vtx) - nxt - 1);
cur = nxt + 1;
}
}
if (Ls.empty() || Rs.empty()) {
return false;
}
for (int L : Ls) {
for (int R : Rs) {
if (L >= R) { continue; }
const int vtx_L = search_vtx[L];
const int vtx_R = search_vtx[R];
const int repr_L = diameter_repr[vtx_L];
const int repr_R = diameter_repr[vtx_R];
const bool is_L_down = (repr_L != vtx_L);
const bool is_R_down = (repr_R != vtx_R);
if (repr_L == repr_R && is_L_down && is_R_down) {
continue;
}
// debug(path_order, L, R);
// Yes-Case 5L: the other path sits in a subtree at loc L
if (is_L_down) {
const i64 len_rooted = len_pref - search_depth[L];
if (FitsRootedPathAndOtherPath(vtx_L + 2 * n, len_rooted, len_inside)) {
debug("Case 5L", vtx_L, repr_L);
return true;
}
}
// Yes-Case 5R: the other path sits in a subtree at loc R
if (is_R_down) {
const i64 len_rooted = len_suf - (search_depth.back() - search_depth[R]);
if (FitsRootedPathAndOtherPath(vtx_R + 2 * n, len_rooted, len_inside)) {
debug("Case 5R", vtx_R, repr_R);
return true;
}
}
// Yes-Case 5X: the other path sits in some different subtree
for (const auto &sip : search_inside_paths) {
const int i = sip.idx;
if (i == L || i == R) { continue; }
if (sip.fit_size >= len_inside) {
const int vtx_i = sip.vtx_i;
debug("Case 5X", vtx_L, vtx_R, vtx_i);
return true;
}
}
}
}
return false;
};
do {
if (CheckPathOrder()) {
debug("Yes-Case 5", path_order);
return true;
}
} while (next_permutation(ALL(path_order)));
return false;
}
void Run() {
Input();
FindAndProcessDiameter();
FindLongSubtreePaths();
PreprocOneAndTwoPathCases();
PreprocDiameterForSearches();
for (int qid = 0; qid < q; ++qid) {
i64 L1, L2, L3;
cin >> L1 >> L2 >> L3;
cout << (SolveQuery({L1, L2, L3}) ? "TAK\n" : "NIE\n");
}
}
};
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(14);
cerr << fixed << setprecision(6);
for (int tid = 0; tid < T; ++tid) {
Testcase{}.Run();
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 | #include <bits/stdc++.h> #define ALL(x) (x).begin(), (x).end() #define SZ(x) ((int)(x).size()) using namespace std; #ifdef LOCAL template<typename A, typename B> auto&operator<<(auto&o,pair<A, B>p){return o<<"("<<p.first<<", "<<p.second<<")";} auto operator<<(auto&o,auto x)->decltype(x.end(),o){o<<"{";int i=0;for(auto e:x)o<<&","[!i++]<<e;return o<<"}";} #define debug(X...)cerr<<"["#X"]: ",[](auto...$){((cerr<<$<<"; "),...)<<endl;}(X) #else #define debug(...){} #endif using i64 = long long; using ll = long long; #define int i64 using pii = pair<int, int>; using pll = pair<i64, i64>; using vi = vector<int>; using vll = vector<i64>; const i64 INF = 2e18; template <typename Tp> void maxi(Tp &a, Tp b) { a = max(a, b); } int T = 1; struct MajorizationContainer { MajorizationContainer() {} vector<pll> items; void AddPair(i64 a, i64 b) { items.emplace_back(a, b); } void Process() { sort(ALL(items)); vector<pll> res; for (const auto [a, b] : items) { while (!res.empty() && res.back().first <= a && res.back().second <= b) { res.pop_back(); } res.emplace_back(a, b); } swap(items, res); } bool IsMajorized(i64 a, i64 b) const { pll cand{a, b}; const auto iter = lower_bound(ALL(items), cand); if (iter == items.end()) { return false; } return (iter->first >= a && iter->second >= b); } }; struct UnsortedLBSearcher { int base; vll data; UnsortedLBSearcher() {} UnsortedLBSearcher(const vll &items) { const int n = SZ(items); base = 1; while (base < n + 5) { base *= 2; } data.resize(base * 2, -INF); for (int i = 0; i < n; ++i) { data[i + base] = items[i]; } data[n + base] = INF; for (int i = base - 1; i > 0; --i) { data[i] = max(data[i * 2], data[i * 2 + 1]); } } int FirstGeqOnSuffix(int start, i64 x) const { int v = start + base; while (data[v] < x) { if (v % 2 == 1) { ++v; } v /= 2; assert(v); } while (v < base) { if (data[v * 2] >= x) { v *= 2; } else { v = v * 2 + 1; } assert(data[v] >= x); } return v - base; } }; struct APlusBSearcher { int base; struct Node { i64 max_a = -INF, max_b = -INF, max_aplusb = -INF; const Node Merge(const Node &rhs) const { Node ans; ans.max_a = max(max_a, rhs.max_a); ans.max_b = max(max_b, rhs.max_b); ans.max_aplusb = max({max_aplusb, rhs.max_aplusb, max_a + rhs.max_b}); return ans; } }; vector<Node> data; APlusBSearcher() {} APlusBSearcher(const vll &A, const vll &B) { debug("APlusBSearcher", A, B); const int n = SZ(A); base = 1; while (base < n + 5) { base *= 2; } data.resize(base * 2); for (int i = 0; i < n; ++i) { data[i + base].max_a = A[i]; data[i + base].max_b = B[i]; } data[n + base].max_aplusb = INF; for (int i = base - 1; i > 0; --i) { data[i] = data[i * 2].Merge(data[i * 2 + 1]); } } int FirstStopWithAPlusBGeqX(int start, i64 x) const { debug("APlusBSearch-Query", start, x); Node cur_pref; int v = start + base; while (cur_pref.Merge(data[v]).max_aplusb < x) { if (v % 2 == 1) { cur_pref = cur_pref.Merge(data[v]); ++v; } v /= 2; assert(v); } debug(base, v); while (v < base) { const Node &cand_pref = cur_pref.Merge(data[v * 2]); if (cand_pref.max_aplusb >= x) { v *= 2; } else { cur_pref = cand_pref; v = v * 2 + 1; } assert(cur_pref.Merge(data[v]).max_aplusb >= x); } const int ans = v - base; debug(ans); return v - base; } }; struct Testcase { int n, q, sz; struct Edge { int to; i64 cost; }; vector<vector<Edge>> graph; vll parent; vll diameter; vll diameter_pos; vll dist_to_diameter; vll diameter_repr; vll depth; vll longest_rooted_path_dn; vll longest_inside_path_dn; vll longest_outside_path_dn; vll longest_rooted_path_up; MajorizationContainer path_pairs_all, path_pairs_nodiag; vector<MajorizationContainer> cloned_subtree_pairs; ll best_nodiag; void AddEdge(int u, int v, i64 c) { // debug(u, v, c); graph[u].push_back({.to = v, .cost = c}); graph[v].push_back({.to = u, .cost = c}); } void Input() { cin >> n; if (n < 0) { // FUNNY HACK assert(T == 1); T = -n; cin >> n; } cin >> q; graph.resize(n + 1); for (int i = 0; i < n - 1; ++i) { int u, v; i64 c; cin >> u >> v >> c; AddEdge(u, v, c); } } int FindFarthest(int v) { function<pair<int, i64>(int, int)> Dfs = [&](int v, int p) { pair<int, i64> ans{v, 0}; for (const auto &edge : graph[v]) { if (edge.to == p) { continue; } auto [s, d] = Dfs(edge.to, v); d += edge.cost; if (d > ans.second) { ans = {s, d}; } } return ans; }; return Dfs(v, -1).first; } vll FindPath(int a, int b) { vll ans; function<bool(int, int)> Dfs = [&](int v, int p) { if (v == a) { ans.push_back(a); return true; } for (const auto &edge : graph[v]) { if (edge.to == p) { continue; } if (Dfs(edge.to, v)) { ans.push_back(v); return true; } } return false; }; const bool ret = Dfs(b, -1); assert(ret); return ans; } void DfsBasicDiameterDepth(int v, int p) { for (const auto &edge : graph[v]) { if (edge.to == p) { continue; } depth[edge.to] = depth[v] + edge.cost; if (diameter_pos[edge.to] == -1) { diameter_repr[edge.to] = diameter_repr[v]; dist_to_diameter[edge.to] = dist_to_diameter[v] + edge.cost; } DfsBasicDiameterDepth(edge.to, v); } } void CloneSubtree(int diameter_vtx, int branch, i64 first_cost) { function<void(int, int)> Dfs = [&](int v, int p) { for (const auto &edge : graph[v]) { const int s = edge.to; if (s == p) { continue; } const int nv = v + n; const int ns = s + n; AddEdge(nv, ns, edge.cost); depth[ns] = depth[nv] + edge.cost; Dfs(s, v); } }; const int nr = branch + n; const int nd = nr + n; debug("Clone", nd, nr, first_cost); AddEdge(nd, nr, first_cost); depth[nd] = 0; depth[nr] = first_cost; Dfs(branch, diameter_vtx); } void FindAndProcessDiameter() { const int diam_end1 = FindFarthest(1); const int diam_end2 = FindFarthest(diam_end1); diameter = FindPath(diam_end1, diam_end2); debug(diameter); diameter_pos.resize(n + 1, -1); diameter_repr.resize(n + 1, -1); for (int i = 0; i < SZ(diameter); ++i) { diameter_pos[diameter[i]] = i; diameter_repr[diameter[i]] = diameter[i]; } dist_to_diameter.resize(n + 1); depth.resize(n + 1); DfsBasicDiameterDepth(diam_end1, -1); debug(diameter_pos); debug(diameter_repr); debug(dist_to_diameter); debug(depth); graph.resize(3 * n + 1); parent.resize(3 * n + 1); depth.resize(3 * n + 1); sz = 3 * n; for (int v : diameter) { for (const auto &edge : graph[v]) { const int s = edge.to; if (diameter_pos[s] != -1) { continue; } CloneSubtree(v, s, edge.cost); } } } void FindLongSubtreePaths() { longest_inside_path_dn.resize(sz + 1, -1); longest_outside_path_dn.resize(sz + 1, -1); longest_rooted_path_dn.resize(sz + 1, -1); longest_rooted_path_up.resize(sz + 1, -1); vector<vll> rooted_cand_lists(sz + 1); vector<vll> inside_cand_lists(sz + 1); function<void(int, int)> DfsDn = [&](int v, int p) { parent[v] = p; longest_rooted_path_dn[v] = longest_inside_path_dn[v] = 0; for (const auto &edge : graph[v]) { if (edge.to == p) { continue; } const int s = edge.to; DfsDn(s, v); const i64 cand = longest_rooted_path_dn[s] + edge.cost; maxi(longest_rooted_path_dn[v], cand); maxi(longest_inside_path_dn[v], longest_inside_path_dn[s]); rooted_cand_lists[v].push_back(cand); inside_cand_lists[v].push_back(longest_inside_path_dn[s]); } sort(ALL(rooted_cand_lists[v]), greater<i64>()); sort(ALL(inside_cand_lists[v]), greater<i64>()); if (!rooted_cand_lists[v].empty()) { maxi(longest_inside_path_dn[v], rooted_cand_lists[v][0]); } if (SZ(rooted_cand_lists[v]) >= 2) { maxi(longest_inside_path_dn[v], rooted_cand_lists[v][0] + rooted_cand_lists[v][1]); } debug(v, longest_rooted_path_dn[v], rooted_cand_lists[v], longest_inside_path_dn[v]); }; function<void(int, int, i64)> DfsUp = [&](int v, int p, i64 cur_up_rooted) { debug(v, p, cur_up_rooted, longest_outside_path_dn[v]); longest_rooted_path_up[v] = cur_up_rooted; if (p != -1) { rooted_cand_lists[v].push_back(cur_up_rooted); sort(ALL(rooted_cand_lists[v]), greater<i64>()); } debug(inside_cand_lists[v]); for (const auto &edge : graph[v]) { if (edge.to == p) { continue; } const int s = edge.to; maxi(longest_outside_path_dn[s], longest_outside_path_dn[v]); if (inside_cand_lists[v][0] != longest_inside_path_dn[s]) { maxi(longest_outside_path_dn[s], inside_cand_lists[v][0]); } else if (SZ(inside_cand_lists[v]) >= 2) { maxi(longest_outside_path_dn[s], inside_cand_lists[v][1]); } i64 next_up_rooted = 0; i64 outside_cand = 0; int num_used = 0; bool is_skipped = false; const i64 skip_cand = longest_rooted_path_dn[s] + edge.cost; for (i64 cand : rooted_cand_lists[v]) { if (cand == skip_cand && !is_skipped) { is_skipped = true; } else { if (num_used == 0) { next_up_rooted = cand; } outside_cand += cand; ++num_used; if (num_used == 2) { break; } } } maxi(longest_outside_path_dn[s], outside_cand); DfsUp(s, v, next_up_rooted + edge.cost); } }; DfsDn(diameter[0], -1); DfsUp(diameter[0], -1, 0); for (int i = 2 * n + 1; i <= 3 * n; ++i) { DfsDn(i, -1); DfsUp(i, -1, 0); } } void PreprocOneAndTwoPathCases() { auto AddCand = [&](MajorizationContainer &dest, i64 a, i64 b) { if (a < b) { swap(a, b); } dest.AddPair(a, b); }; auto AddCandForEdge = [&](MajorizationContainer &dest, int v) { const int pnt = parent[v]; const i64 edge_len = depth[v] - depth[pnt]; AddCand(dest, longest_inside_path_dn[v], longest_outside_path_dn[v]); AddCand(dest, longest_rooted_path_dn[v] + edge_len, longest_outside_path_dn[v]); AddCand(dest, longest_inside_path_dn[v], longest_rooted_path_up[v]); }; for (int v = 1; v <= n; ++v) { if (v != diameter[0]) { AddCandForEdge(path_pairs_all, v); } } path_pairs_all.Process(); debug(path_pairs_all.items); best_nodiag = 0; vll single_paths(2); for (int v = 2 * n + 1; v <= 3 * n; ++v) { single_paths.push_back(longest_inside_path_dn[v]); } for (int v = 1; v <= n; ++v) { if (diameter_pos[v] == -1) { AddCandForEdge(path_pairs_nodiag, v + n); } } sort(ALL(single_paths), greater<i64>()); best_nodiag = single_paths[0]; path_pairs_nodiag.AddPair(single_paths[0], single_paths[1]); path_pairs_nodiag.Process(); debug(path_pairs_nodiag.items); debug(best_nodiag); } bool ContainsPathPair(i64 L1, i64 L2, MajorizationContainer &search_target) { if (L1 < L2) { swap(L1, L2); } return search_target.IsMajorized(L1, L2); } vll search_vertex_start; vll search_vertex_end; vll search_ends; vll search_depth; vll search_addlen; vll search_vtx; struct SearchInsidePaths { int idx; int vtx_i; i64 fit_size; bool operator<(const SearchInsidePaths &other) const { return fit_size < other.fit_size; } bool operator>(const SearchInsidePaths &other) const { return fit_size > other.fit_size; } }; vector<SearchInsidePaths> search_inside_paths; UnsortedLBSearcher search_prefix_inside_lb; UnsortedLBSearcher search_suffix_inside_lb; APlusBSearcher search_aplusb; void PreprocDiameterForSearches() { search_vertex_start.resize(n + 1, -1); search_vertex_end.resize(n + 1, -1); auto InjectInfo = [&](i64 diam_repr, i64 v, i64 rooted_len) { const i64 idx = SZ(search_vtx); search_vtx.push_back(v); search_depth.push_back(depth[diam_repr]); search_addlen.push_back(rooted_len); return idx; }; for (int v : diameter) { search_vertex_start[v] = InjectInfo(v, v, 0); search_ends.push_back(search_vertex_start[v]); for (const auto &edge : graph[v]) { const int s = edge.to; if (diameter_pos[edge.to] != -1) { continue; } InjectInfo(v, s, longest_rooted_path_dn[s + 2 * n]); } search_vertex_end[v] = InjectInfo(v, v, 0); search_ends.push_back(search_vertex_end[v]); } for (int i = 0; i < SZ(search_vtx); ++i) { debug(i, search_vtx[i], search_depth[i], search_addlen[i]); } cloned_subtree_pairs.resize(3 * n + 1); int cur_cloned_root = -1; function<void(int, i64)> DfsRootedAndOther = [&](int v, i64 best_other) { cloned_subtree_pairs[cur_cloned_root].AddPair( depth[v], max(best_other, longest_inside_path_dn[v])); vll cands_inside{0}; vll cands_rooted{0}; for (const auto &edge : graph[v]) { if (edge.to == parent[v]) { continue; } cands_inside.push_back(longest_inside_path_dn[edge.to]); cands_rooted.push_back(longest_rooted_path_dn[edge.to] + edge.cost); } sort(ALL(cands_inside), greater<i64>()); sort(ALL(cands_rooted), greater<i64>()); for (const auto &edge : graph[v]) { if (edge.to == parent[v]) { continue; } i64 inside_cand = cands_inside[0]; if (inside_cand == longest_inside_path_dn[edge.to]) { inside_cand = cands_inside[1]; } i64 rooted_cand = cands_rooted[0]; const i64 rooted_chk = longest_rooted_path_dn[edge.to] + edge.cost; if (rooted_cand == rooted_chk) { rooted_cand = cands_rooted[1]; } const i64 next_other = max({best_other, inside_cand, rooted_cand}); DfsRootedAndOther(edge.to, next_other); } }; for (int v = 2 * n + 1; v <= 3 * n; ++v) { cur_cloned_root = v; DfsRootedAndOther(v, 0); cloned_subtree_pairs[v].Process(); debug(v, cloned_subtree_pairs[v].items); } for (int i = 0; i < SZ(search_vtx); ++i) { const int vtx_i = search_vtx[i]; const int repr_i = diameter_repr[vtx_i]; if (vtx_i == repr_i) { continue; } const i64 fit_size = longest_inside_path_dn[vtx_i + 2 * n]; search_inside_paths.push_back({.idx = i, .vtx_i = vtx_i, .fit_size = fit_size}); } sort(ALL(search_inside_paths), greater<SearchInsidePaths>()); if (SZ(search_inside_paths) > 3) { search_inside_paths.resize(3); } vll data_prefix_inside, data_suffix_inside; for (int i = 0; i < SZ(search_vtx); ++i) { data_prefix_inside.push_back(search_depth[i] + search_addlen[i]); } for (int i = SZ(search_vtx) - 1; i >= 0; --i) { data_suffix_inside.push_back((search_depth.back() - search_depth[i]) + search_addlen[i]); } search_prefix_inside_lb = UnsortedLBSearcher{data_prefix_inside}; search_suffix_inside_lb = UnsortedLBSearcher{data_suffix_inside}; vll aplusb_data_A, aplusb_data_B; for (int i = 0; i < SZ(search_vtx); ++i) { aplusb_data_A.push_back(search_addlen[i] - search_depth[i]); aplusb_data_B.push_back(search_depth[i] + search_addlen[i]); } search_aplusb = APlusBSearcher(aplusb_data_A, aplusb_data_B); } i64 SearchRoundToEnd(i64 R) { if (R >= SZ(search_vtx)) { return SZ(search_vtx); } R = *lower_bound(ALL(search_ends), R); return R; } int FindFirstOnDiameterOfLength(int start, i64 len) { const int ans_fast = search_aplusb.FirstStopWithAPlusBGeqX(start, len); // const int ans_slow = FindFirstOnDiameterOfLengthSlow(start, len); // debug(ans_fast, ans_slow); // assert(ans_fast == ans_slow); return ans_fast; } bool FitsRootedPathAndOtherPath(int root, i64 len_rooted, i64 len_other) { return cloned_subtree_pairs[root].IsMajorized(len_rooted, len_other); } bool SolveQuery(vll lengths) { sort(ALL(lengths), greater<i64>()); // Yes-Case 1: all inside the diameter const i64 diam_length = depth[diameter.back()]; if (lengths[0] + lengths[1] + lengths[2] <= diam_length) { debug("Yes-Case 1"); return true; } // No-Case 1: lengths[0] doesn't fit the diameter if (lengths[0] > diam_length) { debug("No-Case 1"); return false; } // Yes-Case 2: longest inside the diameter, two other outside the diameter if (ContainsPathPair(lengths[1], lengths[2], path_pairs_nodiag)) { debug("Yes-Case 2"); return true; } // Yes-Case 3: There is some path coupling that works for (int outsider : {0, 1, 2}) { const i64 path_a = lengths[0] + lengths[1] + lengths[2] - lengths[outsider]; const i64 path_b = lengths[outsider]; if (ContainsPathPair(path_a, path_b, path_pairs_all)) { debug("Yes-Case 3", outsider, path_a, path_b); return true; } } // Yes-Case 4: All three paths intersect the diameter non-trivially // (i.e., containing internally some point of the diameter) { vll intersect_order = lengths; sort(ALL(intersect_order)); do { i64 loc = 0; for (i64 len : intersect_order) { loc = SearchRoundToEnd(loc); loc = FindFirstOnDiameterOfLength(loc, len); // debug(intersect_order, len, loc); } if (loc < SZ(search_vtx)) { debug("Yes-Case 4", intersect_order); return true; } } while (next_permutation(ALL(intersect_order))); } // Yes-Case 5: One path has the start of the diameter, second has the end of the diameter, // the third does not touch the diameter (non-trivially) vll path_order = lengths; sort(ALL(path_order)); auto CheckPathOrder = [&]() { const i64 len_pref = path_order[0]; const i64 len_suf = path_order[1]; const i64 len_inside = path_order[2]; vector<int> Ls, Rs; { int cur = 0; for (int i = 0; i < 2 && cur < SZ(search_vtx); ++i) { const int nxt = search_prefix_inside_lb.FirstGeqOnSuffix(cur, len_pref); if (nxt >= SZ(search_vtx)) { break; } Ls.push_back(nxt); cur = nxt + 1; } } { int cur = 0; for (int i = 0; i < 2 && cur < SZ(search_vtx); ++i) { const int nxt = search_suffix_inside_lb.FirstGeqOnSuffix(cur, len_suf); if (nxt >= SZ(search_vtx)) { break; } Rs.push_back(SZ(search_vtx) - nxt - 1); cur = nxt + 1; } } if (Ls.empty() || Rs.empty()) { return false; } for (int L : Ls) { for (int R : Rs) { if (L >= R) { continue; } const int vtx_L = search_vtx[L]; const int vtx_R = search_vtx[R]; const int repr_L = diameter_repr[vtx_L]; const int repr_R = diameter_repr[vtx_R]; const bool is_L_down = (repr_L != vtx_L); const bool is_R_down = (repr_R != vtx_R); if (repr_L == repr_R && is_L_down && is_R_down) { continue; } // debug(path_order, L, R); // Yes-Case 5L: the other path sits in a subtree at loc L if (is_L_down) { const i64 len_rooted = len_pref - search_depth[L]; if (FitsRootedPathAndOtherPath(vtx_L + 2 * n, len_rooted, len_inside)) { debug("Case 5L", vtx_L, repr_L); return true; } } // Yes-Case 5R: the other path sits in a subtree at loc R if (is_R_down) { const i64 len_rooted = len_suf - (search_depth.back() - search_depth[R]); if (FitsRootedPathAndOtherPath(vtx_R + 2 * n, len_rooted, len_inside)) { debug("Case 5R", vtx_R, repr_R); return true; } } // Yes-Case 5X: the other path sits in some different subtree for (const auto &sip : search_inside_paths) { const int i = sip.idx; if (i == L || i == R) { continue; } if (sip.fit_size >= len_inside) { const int vtx_i = sip.vtx_i; debug("Case 5X", vtx_L, vtx_R, vtx_i); return true; } } } } return false; }; do { if (CheckPathOrder()) { debug("Yes-Case 5", path_order); return true; } } while (next_permutation(ALL(path_order))); return false; } void Run() { Input(); FindAndProcessDiameter(); FindLongSubtreePaths(); PreprocOneAndTwoPathCases(); PreprocDiameterForSearches(); for (int qid = 0; qid < q; ++qid) { i64 L1, L2, L3; cin >> L1 >> L2 >> L3; cout << (SolveQuery({L1, L2, L3}) ? "TAK\n" : "NIE\n"); } } }; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(14); cerr << fixed << setprecision(6); for (int tid = 0; tid < T; ++tid) { Testcase{}.Run(); } } |
English