CF 258E Little Elephant and Tree 【线段树,树上DFS序列】

来源:互联网 发布:web编程入门c# 编辑:程序博客网 时间:2024/06/01 14:18

题意:对一颗树进行m次操作,每次操作(a,b)都是在节点a和b的子树的所有节点后边加入操作的序号。最后询问每个节点分别与多少个其他节点拥有相同的操作编号。

英文题解:http://codeforces.com/blog/entry/6213

首先根据DFS顺序将树转化为一个线段树,剩下的问题就可以用线段树来解决了。

如果节点x进行了第i种操作,那么x所有的儿子节点也都进行了相同的操作,只需要将每个节点的祖先节点的操作都记录下来,当前被覆盖的区间的长度就是:和节点x具有相同操作的节点个数。

因此,只需要一边深搜,一边进行操作就可以了。(具体看代码的work函数)



#include <cstdio>#include <iostream>#include <algorithm>#include <vector>#include <cstring>using namespace std;#define N 100100int n, m, c[N], p[N], cnt, ans[N];int lz[N<<2], cc[N<<2];vector<int> g[N];vector<int> q[N];void dfs(int now, int fa) {    p[now] = ++cnt;    c[now] = 1;    int u;    for (int i=0; i<g[now].size(); i++)        if ((u = g[now][i]) != fa) {            dfs(u, now);            c[now] += c[u];        }}void Up(int L, int R, int rt) {    if (lz[rt]) cc[rt] = R-L+1;    else {        if (L == R) cc[rt] = 0;        else cc[rt] = cc[rt<<1] + cc[rt<<1|1];    }}void update(int l, int r, int add, int L, int R, int rt) {    if (l <= L && R <= r) {        lz[rt] += add;        Up(L, R, rt);        return ;    }    int mid = (L + R) >> 1;    if (l <= mid) update(l, r, add, L, mid, rt<<1);    if (mid < r) update(l, r, add, mid+1, R, rt<<1|1);    Up(L, R, rt);}void work(int now, int fa) {    int u;    for (int i=0; i<q[now].size(); i++) {        u = q[now][i];        update(p[u], p[u]+c[u]-1, 1, 1, n, 1);    }    ans[now] = cc[1];    if (ans[now]) ans[now]--;    for (int i=0; i<g[now].size(); i++)        if ((u=g[now][i]) != fa) {            work(u, now);        }    for (int i=0; i<q[now].size(); i++) {        u = q[now][i];        update(p[u], p[u]+c[u]-1, -1, 1, n, 1);    }}int main() {    scanf("%d%d", &n, &m);    int x, y;    for (int i=1; i<n; i++) {        scanf("%d%d", &x, &y);        g[x].push_back(y);        g[y].push_back(x);    }    cnt = 0;    dfs(1, 0);    for (int i=0; i<m; i++) {        scanf("%d%d", &x, &y);        q[x].push_back(y), q[x].push_back(x);        q[y].push_back(x), q[y].push_back(y);    }    memset(lz, 0, sizeof(lz));    memset(cc, 0, sizeof(cc));    work(1, 0);    for (int i=1; i<=n; i++) printf("%d ", ans[i]);    return 0;}


原创粉丝点击