POJ-2763 Housewife Wind
作者:互联网
Housewife Wind
树链剖分
利用树中每个点都只有一个父节点的性质,将边权化为点权,然后树链剖分 LCA,套一个线段树维护权值
注意在同一链的时候,LCA 的点权是不计算在内的
这题卡时间卡的很紧,如果 TLE,尝试改成 scanf printf
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1e5 + 10;
#define pii pair<int, int>
int hson[maxn], siz[maxn], fa[maxn], dep[maxn];
int dfn[maxn], top[maxn], rnk[maxn];
int w[maxn], id[maxn], p[maxn];
int tr[maxn << 2];
vector<pii>gra[maxn];
void build(int now, int l, int r)
{
if(l == r)
{
tr[now] = w[p[rnk[l]]];
return;
}
int mid = l + r >> 1;
build(now << 1, l, mid);
build(now << 1 | 1, mid + 1, r);
tr[now] = tr[now << 1] + tr[now << 1 | 1];
}
void update(int now, int l, int r, int x, int val)
{
if(l == r)
{
tr[now] = val;
return;
}
int mid = l + r >> 1;
if(x <= mid)
update(now << 1, l, mid, x, val);
else
update(now << 1 | 1, mid + 1, r, x, val);
tr[now] = tr[now << 1] + tr[now << 1 | 1];
}
int query(int now, int l, int r, int L, int R)
{
if(L <= l && r <= R)
return tr[now];
int mid = l + r >> 1;
int ans = 0;
if(L <= mid)
ans += query(now << 1, l, mid, L, R);
if(R > mid)
ans += query(now << 1 | 1, mid + 1, r, L, R);
return ans;
}
void dfs1(int now, int cnt)
{
siz[now] = 1;
hson[now] = 0;
dep[now] = cnt;
for(int i=0; i<gra[now].size(); i++)
{
int nex = gra[now][i].first;
int x = gra[now][i].second;
if(nex == fa[now]) continue;
fa[nex] = now;
id[x] = nex;
p[nex] = x;
dfs1(nex, cnt + 1);
siz[now] += siz[nex];
if(siz[hson[now]] < siz[nex])
hson[now] = nex;
}
}
int tp = 0;
void dfs2(int now, int t)
{
tp++;
dfn[now] = tp;
rnk[tp] = now;
top[now] = t;
if(hson[now])
{
dfs2(hson[now], t);
for(int i=0; i<gra[now].size(); i++)
{
int nex = gra[now][i].first;
if(nex == fa[now] || nex == hson[now]) continue;
dfs2(nex, nex);
}
}
}
void init(int n, int rt)
{
tp = 0;
fa[rt] = rt;
dfs1(rt, 1);
dfs2(rt, rt);
build(1, 1, n);
}
int LCA(int a, int b, int n)
{
int ans = 0;
while(top[a] != top[b])
{
if(dep[top[a]] < dep[top[b]]) swap(a, b);
ans += query(1, 1, n, dfn[top[a]], dfn[a]);
a = fa[top[a]];
}
if(dfn[a] > dfn[b]) swap(a, b);
if(a != b)
ans += query(1, 1, n, dfn[a] + 1, dfn[b]);
return ans;
}
int main()
{
int n, q, rt;
scanf("%d%d%d", &n, &q, &rt);
for(int i=1; i<n; i++)
{
int x, y;
scanf("%d%d%d", &x, &y, &w[i]);
gra[x].push_back(make_pair(y, i));
gra[y].push_back(make_pair(x, i));
}
init(n, rt);
while(q--)
{
int t;
scanf("%d", &t);
if(t == 1)
{
int i, x;
scanf("%d%d", &i, &x);
update(1, 1, n, dfn[id[i]], x);
}
else
{
int u;
scanf("%d", &u);
printf("%d\n", LCA(rt, u, n));
swap(rt, u);
}
}
return 0;
}
标签:now,2763,int,dfn,maxn,ans,POJ,include,Wind 来源: https://www.cnblogs.com/dgsvygd/p/16450977.html