luogu4074 [WC2013]糖果公园(树上带修莫队)

代码先放着,题解鸽了233

明天补

#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

struct fuck { int x, y, id; } a[200010];
int n, m, q, sz, top, tot, bcnt;
int v[200010], bid[200010], bucket[200010];
int fa[200010][19], s[200010], c[200010], tmp[200010];
vector<int> out[200010];
int pos[200010], from[200010], to[200010], depth[200010];
bool in[200010];
long long sum, ans[200010], w[200010];

bool fucked(const fuck &a, const fuck &b)
{
    if (bid[a.x] != bid[b.x]) return bid[a.x] < bid[b.x];
    if (bid[a.y] != bid[b.y]) return bid[a.y] < bid[b.y];
    return a.id < b.id;
}

void dfs(int x)
{
    int tmp = top;
    for (int i : out[x]) if (fa[x][0] != i)
    {
        fa[i][0] = x, depth[i] = depth[x] + 1, dfs(i);
        if (top - tmp >= sz) { bcnt++; while (top != tmp) bid[s[top--]] = bcnt; }
    }
    s[++top] = x;
}

int lca(int x, int y)
{
    if (depth[x] < depth[y]) swap(x, y);
    for (int i = 18; i >= 0; i--) if (depth[fa[x][i]] >= depth[y]) x = fa[x][i];
    if (x == y) return x;
    for (int i = 18; i >= 0; i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
    return fa[x][0];
}

void del(int x) { sum -= v[x] * w[bucket[x]]; bucket[x]--; sum += v[x] * w[bucket[x]]; }
void add(int x) { sum -= v[x] * w[bucket[x]]; bucket[x]++; sum += v[x] * w[bucket[x]]; }
void chenge(int x) { if (in[x]) del(c[x]); else add(c[x]); in[x] ^= 1; }
void chenge(int x, int y)
{
    int lc = lca(x, y);
    while (x != lc) chenge(x), x = fa[x][0];
    while (y != lc) chenge(y), y = fa[y][0];
}

int main()
{
    scanf("%d%d%d", &n, &m, &q), sz = cbrt(n), sz = sz * sz;
    for (int i = 1; i <= m; i++) scanf("%d", &v[i]);
    for (int i = 1; i <= n; i++) scanf("%lld", &w[i]), w[i] += w[i - 1];
    for (int x, y, i = 1; i < n; i++) scanf("%d%d", &x, &y), out[x].push_back(y), out[y].push_back(x);
    for (int i = 1; i <= n; i++) scanf("%d", &c[i]), tmp[i] = c[i];
    depth[1] = 1, dfs(1); if (top == 0) { top++; } while (top) bid[s[top--]] = bcnt;
    for (int j = 1; j <= 18; j++) for (int i = 1; i <= n; i++) fa[i][j] = fa[fa[i][j - 1]][j - 1];
    for (int opd, x, y, i = 1; i <= q; i++)
    {
        scanf("%d%d%d", &opd, &x, &y);
        if (opd) { if (bid[x] > bid[y]) { swap(x, y); } a[++tot] = (fuck){x, y, i}; }
        else pos[i] = x, from[i] = tmp[x], tmp[x] = y, to[i] = y;
    }
    sort(a + 1, a + 1 + tot, fucked);
    for (int x = 1, y = 1, t = 0, i = 1; i <= tot; i++)
    {
        chenge(x, a[i].x), chenge(y, a[i].y), x = a[i].x, y = a[i].y;
        for (; t < a[i].id; t++) if (pos[t]) { c[pos[t]] = to[t]; if (in[pos[t]]) del(from[t]), add(to[t]); }
        for (; t > a[i].id; t--) if (pos[t]) { c[pos[t]] = from[t]; if (in[pos[t]]) del(to[t]), add(from[t]); }
        add(c[lca(x, y)]), ans[a[i].id] = sum, del(c[lca(x, y)]);
    }
    for (int i = 1; i <= q; i++) if (pos[i] == 0) printf("%lld\n", ans[i]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/oier/p/10604279.html