CF600E Lomsat gelral(线段树合并)

link

题目大意:给以1为根的一棵树,求树上每个点子树中出现次数最多的权值(如果有多个就求他们的和)

对每个点开一个线段树维护子树内权值的桶,dfs时候线段树合并就行了。

因为最后线段树一共插入最多 \(O(n\log n)\) 个节点,每个节点最多会被合并一次,所以复杂度是 \(O(n\log n)\) 的。

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

struct fuck { int maxval; long long sum; } tree[2333333];
int lc[2333333], rc[2333333], tot;
int n, val[100010], fa[100010], rt[100010];
vector<int> out[100010];
long long ans[100010];

fuck operator*(const fuck &a, const fuck &b)
{
    if (a.maxval > b.maxval) return a;
    if (a.maxval < b.maxval) return b;
    return (fuck){a.maxval, a.sum + b.sum};
}

int mg(int x1, int x2, int cl, int cr)
{
    if (x1 == 0) return x2;
    if (x2 == 0) return x1;
    if (cl == cr)
    {
        tree[x1] = (fuck){tree[x1].maxval + tree[x2].maxval, tree[x1].sum};
        return x1;
    }
    int mid = (cl + cr) / 2;
    lc[x1] = mg(lc[x1], lc[x2], cl, mid);
    rc[x1] = mg(rc[x1], rc[x2], mid + 1, cr);
    tree[x1] = tree[lc[x1]] * tree[rc[x1]];
    return x1;
}

void chenge(int &x, int cl, int cr, int pos, int val)
{
    if (x == 0) x = ++tot;
    if (cl == cr) { tree[x].maxval++; tree[x].sum = cl; return; }
    int mid = (cl + cr) / 2;
    if (pos > mid) chenge(rc[x], mid + 1, cr, pos, val);
    else chenge(lc[x], cl, mid, pos, val);
    tree[x] = tree[lc[x]] * tree[rc[x]];
}

void dfs(int x)
{
    for (int i : out[x]) if (fa[x] != i)
    {
        fa[i] = x; dfs(i), rt[x] = mg(rt[x], rt[i], 1, n);
    }
    chenge(rt[x], 1, n, val[x], 1);
    ans[x] = tree[rt[x]].sum;
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d", &val[i]);
    for (int x, y, i = 1; i < n; i++)
    {
        scanf("%d%d", &x, &y);
        out[x].push_back(y), out[y].push_back(x);
    }
    dfs(1);
    for (int i = 1; i <= n; i++) printf("%I64d ", ans[i]);
    return 0;
}
上一篇:node.js环境搭建&npm配置(win7)


下一篇:CF600E Lomsat gelral