P4114 Qtree1
Sol
树剖板子。
#include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define pf push_front
#define desktop "C:\\Users\\incra\\Desktop\\"
#define IOS ios :: sync_with_stdio (false),cin.tie (0),cout.tie (0)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair <int,int> PII;
const int dx[] = {1,0,-1,0},dy[] = {0,-1,0,1};
template <typename T1,typename T2> bool tomax (T1 &x,T2 y) {
if (y > x) return x = y,true;
return false;
}
template <typename T1,typename T2> bool tomin (T1 &x,T2 y) {
if (y < x) return x = y,true;
return false;
}
LL power (LL a,LL b,LL p) {
LL ans = 1;
while (b) {
if (b & 1) ans = ans * a % p;
a = a * a % p;
b >>= 1;
}
return ans;
}
int fastio = (IOS,0);
#define endl '\n'
#define puts(s) cout << (s) << endl
#define int LL
const int N = 100010;
int n;
vector <PII> g[N];
int w[N];
int sz[N],son[N],fa[N],dep[N];
int top[N],dfn[N],timestamp;
struct node {
int a,b,w;
}e[N];
struct seg_node {
int l,r;
int maxx;
}tr[4 * N];
void push_up (int u) {
tr[u].maxx = max (tr[u << 1].maxx,tr[u << 1 | 1].maxx);
}
void build (int u,int l,int r) {
tr[u] = {l,r,0};
if (l == r) return ;
int mid = l + r >> 1;
build (u << 1,l,mid),build (u << 1 | 1,mid + 1,r);
}
void modify (int u,int x,int d) {
if (tr[u].l == tr[u].r) {
tr[u].maxx = d;
return ;
}
int mid = tr[u].l + tr[u].r >> 1;
if (x <= mid) modify (u << 1,x,d);
else modify (u << 1 | 1,x,d);
push_up (u);
}
int query (int u,int l,int r) {
if (l <= tr[u].l && tr[u].r <= r) return tr[u].maxx;
int mid = tr[u].l + tr[u].r >> 1;
int ans = 0;
if (l <= mid) tomax (ans,query (u << 1,l,r));
if (r >= mid + 1) tomax (ans,query (u << 1 | 1,l,r));
return ans;
}
void DFS1 (int u,int _fa) {
fa[u] = _fa;
sz[u] = 1;
for (auto [v,_w] : g[u]) {
if (v == _fa) continue;
dep[v] = dep[u] + 1;
w[v] = _w;
DFS1 (v,u);
sz[u] += sz[v];
if (sz[v] > sz[son[u]]) son[u] = v;
}
}
void DFS2 (int u,int top_node) {
dfn[u] = ++timestamp;
top[u] = top_node;
if (!son[u]) return ;
DFS2 (son[u],top_node);
for (auto [v,w] : g[u]) {
if (v == fa[u] || v == son[u]) continue;
DFS2 (v,v);
}
}
int query_path (int x,int y) {
if (x == y) return 0;
int ans = 0;
while (top[x] != top[y]) {
if (dep[top[x]] < dep[top[y]]) swap (x,y);
tomax (ans,query (1,dfn[top[x]],dfn[x]));
x = fa[x];
}
if (dep[x] > dep[y]) swap (x,y);
tomax (ans,query (1,dfn[x] + 1,dfn[y]));
return ans;
}
void mian () {
cin >> n;
for (int i = 1;i <= n - 1;i++) {
int a,b,c;
cin >> a >> b >> c;
e[i] = {a,b,c};
g[a].pb ({b,c}),g[b].pb ({a,c});
}
build (1,1,n);
DFS1 (1,0),DFS2 (1,1);
for (int i = 2;i <= n;i++) modify (1,dfn[i],w[i]);
string op;
while (cin >> op) {
if (op == "DONE") break;
if (op == "CHANGE") {
int x,t;
cin >> x >> t;
int a = e[x].a,b = e[x].b;
if (dep[a] < dep[b]) swap (a,b);
x = a;
modify (1,dfn[x],t);
w[x] = t;
}
else {
int x,y;
cin >> x >> y;
cout << query_path (x,y) << endl;
}
}
}
signed main () {
int T = 1;
// cin >> T;
while (T--) mian ();
return 0;
}

浙公网安备 33010602011771号