作者: KSkun

[SPOJ-QTREE6]Query on a tree VI 题解

[SPOJ-QTREE6]Query on a tree VI 题解

题目地址:洛谷:【SP16549】QTREE6 – Query on a tree VI – 洛谷、SPOJ:SPOJ.com – Problem QTREE6

SPOJ QTREE系列:

题目描述

You are given a tree (an acyclic undirected connected graph) with n nodes. The tree nodes are numbered from 1 to n. Each node has a color, white or black. All the nodes are black initially. We will ask you to perform some instructions of the following form:

  • 0 u: ask for how many nodes are connected to u, two nodes are connected if all the node on the path from u to v (inclusive u and v) have the same color.
  • 1 u: toggle the color of u (that is, from black to white, or from white to black).

给一棵树,最初点全是黑色的,操作:1.询问到u路径颜色相同的点有多少个2.改变颜色

输入输出格式

输入格式:
The first line contains a number n that denotes the number of nodes in the tree (1 ≤ n ≤ 10^5). In each of the following n-1 lines, there will be two numbers (u, v) that describes an edge of the tree (1 ≤ u, v ≤ n). The next line contains a number m denoting number of operations we are going to process (1 ≤ m ≤ 10^5). Each of the following m lines describe an operation (t, u) as we mentioned above(0 ≤ t ≤ 1, 1 ≤ u ≤ n).

输出格式:
For each query operation, output the corresponding result.

输入输出样例

输入样例#1:

5
1 2
1 3
1 4
1 5
3
0 1
1 1
0 1

输出样例#1:

5
1

输入样例#2:

7
1 2
1 3
2 4
2 5
3 6
3 7
4
0 1
1 1
0 2
0 3

输出样例#2:

7
3
3

题解

参考资料:【Qtree】Query on a tree系列LCT解法 – CSDN博客
本题还是可以用边分……等等这题边分我做不动了,用的LCT。
我们考虑搞两棵LCT对应黑和白色的点构成的树。这样其实查询就变成了某一棵树上的子树大小查询。这个可以用子树信息LCT方便地维护。具体来说,就是统计一下跟当前点相连的轻边子树大小和Splay子树大小加起来。access的时候边合并Splay边更新轻边子树大小即可。
但是如果改变颜色的时候强行切边,有可能被菊花图卡掉。我们考虑把原树拉成一棵有根树,只切该点和父亲的边,这样,这棵LCT就满足所有儿子肯定同色,但是这个父亲可以跟儿子不同色这样的性质。我们在统计答案的时候找到子树根,然后看看子树根是否和儿子的颜色一致,不一致就取儿子的答案即可。
有一个小优化,可以DFS建树,把原树的边建成LCT上的轻边就好。

代码

// Code by KSkun, 2018/3
#include <cstdio>
#include <cstring>

#include <algorithm>

inline char fgc() {
    static char buf[100000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

inline int readint() {
    register int res = 0, neg = 1;
    char c = fgc();
    while(c < '0' || c > '9') {
        if(c == '-') neg = -1;
        c = fgc();
    }
    while(c >= '0' && c <= '9') {
        res = res * 10 + c - '0';
        c = fgc();
    }
    return res * neg;
}

const int MAXN = 100005, INF = 1e9;

struct Edge {
    int to, w, nxt;
} gra[MAXN << 1];
int head[MAXN], ecnt, fa[MAXN], col[MAXN];

inline void addedge(int u, int v, int w) {
    gra[ecnt] = Edge {v, w, head[u]}; head[u] = ecnt++;
}

struct LCT {
    struct LCTNode {
        int ch[2], fa, siz, s;
        bool rev;
    } lct[MAXN];

    inline bool isleft(int p) {
        return lct[lct[p].fa].ch[0] == p;
    }

    inline bool isroot(int p) {
        register int fa = lct[p].fa;
        return lct[fa].ch[0] != p && lct[fa].ch[1] != p;
    }

    inline void update(int p) {
        register int ls = lct[p].ch[0], rs = lct[p].ch[1];
        lct[p].siz = lct[p].s + lct[ls].siz + lct[rs].siz + 1;
    }

    inline void reverse(int p) {
        std::swap(lct[p].ch[0], lct[p].ch[1]);
        lct[p].rev ^= 1;
    }

    inline void pushdown(int p) {
        register int ls = lct[p].ch[0], rs = lct[p].ch[1];
        if(lct[p].rev) {
            if(ls) reverse(ls);
            if(rs) reverse(rs);
            lct[p].rev ^= 1;
        }
    }

    int sta[MAXN], stop;

    inline void pushto(int p) {
        stop = 0;
        while(!isroot(p)) {
            sta[stop++] = p;
            p = lct[p].fa;
        }
        pushdown(p);
        while(stop) {
            pushdown(sta[--stop]);
        }
    }

    inline void rotate(int p) {
        register bool t = !isleft(p); register int fa = lct[p].fa, ffa = lct[fa].fa;
        lct[p].fa = ffa; if(!isroot(fa)) lct[ffa].ch[!isleft(fa)] = p;
        lct[fa].ch[t] = lct[p].ch[!t]; lct[lct[fa].ch[t]].fa = fa;
        lct[p].ch[!t] = fa; lct[fa].fa = p;
        update(fa);
    }

    inline void splay(int p) {
        pushto(p);
        for(register int fa = lct[p].fa; !isroot(p); rotate(p), fa = lct[p].fa) {
            if(!isroot(fa)) rotate(isleft(fa) == isleft(p) ? fa : p);
        }
        update(p);
    }

    inline void access(int p) {
        for(register int q = 0; p; q = p, p = lct[p].fa) {
            splay(p);
            if(lct[p].ch[1]) lct[p].s += lct[lct[p].ch[1]].siz;
            if(q) lct[p].s -= lct[q].siz;
            lct[p].ch[1] = q;
            update(p);
        }
    }

    inline void makert(int p) {
        access(p);
        splay(p);
        reverse(p);
    }

    inline int findrt(int p) {
        access(p);
        splay(p);
        while(lct[p].ch[0]) p = lct[p].ch[0];
        return p;
    }

    inline void link(int u) {
        access(fa[u]);
        splay(fa[u]);
        splay(u);
        lct[fa[u]].ch[1] = u;
        lct[u].fa = fa[u];
        update(fa[u]);
    }

    inline void cut(int u) {
        access(u);
        splay(u);
        lct[u].ch[0] = lct[lct[u].ch[0]].fa = 0;
        update(u);
    }

    inline int query(int u) {
        int c = col[u];
        u = findrt(u);
        splay(u);
        return col[u] == c ? lct[u].siz : lct[lct[u].ch[1]].siz;
    }
} L[2];

inline void dfs(int u, int f) {
    for(int i = head[u]; ~i; i = gra[i].nxt) {
        int v = gra[i].to;
        if(v == f) continue;
        fa[v] = L[0].lct[v].fa = u;
        dfs(v, u);
        L[0].lct[u].s += L[0].lct[v].siz;
    }
    L[0].update(u);
}

int n, q, ut, vt, op;

int main() {
    memset(head, -1, sizeof(head));
    n = readint();
    for(int i = 1; i < n; i++) {
        ut = readint(); vt = readint();
        addedge(ut, vt, 1);
        addedge(vt, ut, 1);
    }
    dfs(1, 0);
    q = readint();
    while(q--) {
        op = readint(); ut = readint();
        if(!op) {
            printf("%d\n", L[col[ut]].query(ut));
        } else {
            if(fa[ut]) {
                L[col[ut]].cut(ut);
                L[col[ut] ^ 1].link(ut);
            }
            col[ut] ^= 1;
        }
    }
    return 0;
}
边分治原理及实现

边分治原理及实现

树分治系列:

概述

点分治是一种分治策略,其核心在于寻找子树的中心边,从中心边的两个点分治解决,从而优化复杂度,实现O(\log n)的分治复杂度(不含分治中的处理复杂度)。

原理与实现

重构树(非必须)

由于某些树对边分治不利(例如:深度只有1的树/菊花图),我们需要重构树。重构后的树满足一个点的度数不超过3,即为一棵二叉树。
重构树的过程是,先将儿子的重构解决完毕,再将儿子二分接到虚点上,虚点的设置需要不影响之后的答案计算。

inline void rebuild(int u, int fa) {
    int ff = 0;
    for(int i = heado[u]; ~i; i = grao[i].nxt) {
        int v = grao[i].to, w = grao[i].w;
        if(v == fa) continue;
        if(!ff) {
            addedge(u, v, w);
            addedge(v, u, w);
            ff = u;
        } else {
            int k = ++n;
            addedge(ff, k, 0);
            addedge(k, ff, 0);
            addedge(k, v, w);
            addedge(v, k, w);
            ff = k;
        }
        rebuild(v, u);
    }
}

找中心边

分治的第一步是找到重心。中心边是指树中满足两个端点对应子树中较大的大小最小的边,这样的边满足其端点子树大小分布比较平衡,可以更好地缩小问题规模。在实际操作中,我们设计递归算法,将一个边的左右两个子树统计出来。递归的时候注意将当前中心边打上删除标记,避免统计串子树了。

inline void findct(int u, int fa) {
    siz[u] = 1;
    for(int i = head[u]; ~i; i = gra[i].nxt) {
        int v = gra[i].to;
        if(del[i >> 1] || v == fa) continue;
        findct(v, u);
        siz[u] += siz[v];
        int vsiz = std::max(siz[v], sum - siz[v]);
        if(vsiz < ctsiz) {
            ct = i;
            ctsiz = vsiz;
        }
    }
}

处理问题的流程

既然是分治,我们就要考虑分治的流程。

  1. 找到两个子树的中心边,递归到子树中心边去解决子问题
  2. 将子树的答案合并至当前树根

例题:点连接去看:SPOJ – QTREE4

参考资料

[SPOJ-QTREE2]Query on a tree II 题解

[SPOJ-QTREE2]Query on a tree II 题解

题目地址:洛谷:【SP913】QTREE2 – Query on a tree II – 洛谷、SPOJ:SPOJ.com – Problem QTREE2

SPOJ QTREE系列:

题目描述

You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, 3…N-1. Each edge has an integer value assigned to it, representing its length.
We will ask you to perfrom some instructions of the following form:

  • DIST a b : ask for the distance between node a and node b
  • KTH a b k : ask for the k-th node on the path from node a to node b

给一棵带边权的树,操作1.询问两点路径长2.求两点有向路径上第k点。

输入输出格式

输入格式:
The first line of input contains an integer t, the number of test cases (t <= 25). t test cases follow.
For each test case:

  • In the first line there is an integer N (N <= 10000)
  • In the next N-1 lines, the i-th line describes the i-th edge: a line with three integers a b c denotes an edge between a, b of cost c (c <= 100000)
  • The next lines contain instructions “DIST a b” or “KTH a b k”
  • The end of each test case is signified by the string “DONE”.

There is one blank line between successive tests.

输出格式:
For each “DIST” or “KTH” operation, write one integer representing its result.
Print one blank line after each test.

输入输出样例

输入样例#1:

1

6
1 2 1
2 4 1
2 5 2
1 3 1
3 6 2
DIST 4 6
KTH 4 6 4
DONE

输出样例#1:

5
3

题解

求和同QTREE:[SPOJ-QTREE]Query on a tree 题解 | KSkun’s Blog。查k点可以考虑算一下LCA到两个儿子的距离,看看这个点在哪条链上,然后再换算成底端往上第几个点,沿重链上跳,利用DFS序算出来即可。

代码

// Code by KSkun, 2018/3
#include <cstdio>
#include <cstring>

#include <vector>
#include <algorithm>

typedef long long LL;

inline char fgc() {
    static char buf[100000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

inline int readint() {
    register int res = 0, neg = 1;
    register char c = fgc();
    while(c < '0' || c > '9') {
        if(c == '-') neg = -1;
        c = fgc();
    }
    while(c >= '0' && c <= '9') {
        res = res * 10 + c - '0';
        c = fgc();
    }
    return res * neg;
}

inline bool isop(char c) {
    return c == 'I' || c == 'H' || c == 'O';
}

inline char readop() {
    register char c;
    while(!isop(c = fgc()));
    return c;
}

const int MAXN = 10005;

struct Edge {
    int to, w, nxt;
} gra[MAXN << 1];
int head[MAXN], tot;

int T, n, m, ut, vt, wt, kt;
char op;
int w[MAXN], fa[MAXN], siz[MAXN], son[MAXN], dfn[MAXN], ptn[MAXN], top[MAXN], dep[MAXN], cnt;

inline void dfs1(int u) {
    siz[u] = 1;
    son[u] = 0;
    for(register int i = head[u]; i; i = gra[i].nxt) {
        register int v = gra[i].to;
        if(v == fa[u]) continue;
        dep[v] = dep[u] + 1;
        fa[v] = u;
        w[v] = gra[i].w;
        dfs1(v);
        siz[u] += siz[v];
        if(siz[v] > siz[son[u]]) son[u] = v;
    }
}

inline void dfs2(int u, int tp) {
    top[u] = tp;
    dfn[u] = ++cnt;
    ptn[dfn[u]] = u;
    if(son[u]) dfs2(son[u], tp);
    for(register int i = head[u]; i; i = gra[i].nxt) {
        register int v = gra[i].to;
        if(v == son[u] || v == fa[u]) continue;
        dfs2(v, v);
    }
}

LL sgt[MAXN << 2];

inline void build(int o, int l, int r) {
    if(l == r) {
        sgt[o] = w[ptn[l]];
        return;
    }
    register int mid = (l + r) >> 1, lch = o << 1, rch = (o << 1) | 1;
    build(lch, l, mid);
    build(rch, mid + 1, r);
    sgt[o] = sgt[lch] + sgt[rch];
}

inline void modify(int o, int l, int r, int x, int v) {
    if(l == r) {
        sgt[o] = v;
        return;
    }
    register int mid = (l + r) >> 1, lch = o << 1, rch = (o << 1) | 1;
    if(x <= mid) modify(lch, l, mid, x, v);
    else modify(rch, mid + 1, r, x, v);
    sgt[o] = sgt[lch] + sgt[rch];
}

inline LL query(int o, int l, int r, int ll, int rr) {
    if(l >= ll && r <= rr) {
        return sgt[o];
    }
    register int mid = (l + r) >> 1, lch = o << 1, rch = (o << 1) | 1;
    register LL res = 0;
    if(ll <= mid) res += query(lch, l, mid, ll, rr);
    if(rr > mid) res += query(rch, mid + 1, r, ll, rr);
    return res;
}

inline LL querysum(int u, int v) {
    int tu = top[u], tv = top[v];
    register LL res = 0;
    while(tu != tv) {
        if(dep[tu] > dep[tv]) {
            std::swap(u, v);
            std::swap(tu, tv);
        }
        res += query(1, 1, n, dfn[tv], dfn[v]);
        v = fa[tv];
        tv = top[v];
    }
    if(dep[u] > dep[v]) std::swap(u, v);
    if(u != v) res += query(1, 1, n, dfn[u] + 1, dfn[v]);
    return res;
}

inline int querylca(int u, int v) {
    int tu = top[u], tv = top[v];
    while(tu != tv) {
        if(dep[tu] > dep[tv]) {
            std::swap(u, v);
            std::swap(tu, tv);
        }
        v = fa[tv];
        tv = top[v];
    }
    if(dep[u] > dep[v]) std::swap(u, v);
    return u;
}

inline int querykth(int u, int v, int k) {
    int lca = querylca(u, v), tu = top[u], tv = top[v];
    if(dep[u] - dep[lca] + 1 >= k) {
        while(dep[tu] > dep[lca]) {
            if(dep[u] - dep[tu] + 1 >= k) break;
            k -= dep[u] - dep[tu] + 1;
            u = fa[tu];
            tu = top[u];
        }
        return ptn[dfn[u] - k + 1];
    } else {
        k -= dep[u] - dep[lca] + 1;
        k = dep[v] - dep[lca] - k + 1;
        while(dep[tv] > dep[lca]) {
            if(dep[v] - dep[tv] + 1 >= k) break;
            k -= dep[v] - dep[tv] + 1;
            v = fa[tv];
            tv = top[v];
        }
        return ptn[dfn[v] - k + 1];
    }
}

inline void addedge(int u, int v, int w) {
    gra[++tot] = Edge {v, w, head[u]};
    head[u] = tot;
}

int main() {
    T = readint();
    while(T--) {
        tot = cnt = 0;
        memset(head, 0, sizeof(head));
        n = readint();
        for(int i = 1; i < n; i++) {
            ut = readint(); vt = readint(); wt = readint();
            addedge(ut, vt, wt);
            addedge(vt, ut, wt);
        }
        dfs1(1);
        dfs2(1, 1);
        build(1, 1, n);
        for(;;) {
            op = readop();
            if(op == 'O') break;
            ut = readint();
            vt = readint();
            if(op == 'I') {
                printf("%lld\n", querysum(ut, vt));
            } else {
                kt = readint();
                printf("%d\n", querykth(ut, vt, kt));
            }
        }
        printf("\n");
    }
    return 0;
}