D. Ralph And His Tour in Binary Country

来源:互联网 发布:金山旗下软件 编辑:程序博客网 时间:2024/06/06 03:56

传送门

http://codeforces.com/problemset/problem/894/D

给出一个平衡的二叉树,带边权,每组询问等价于求到A点距离不超过H的所有点到A点的距离和。

思考为什么是“平衡二叉树”,其具有层数不超过logn,只有每个节点最多有两个子的特点。
对每个点将其子树所有点到该点的距离维护成一个有序表,由于是静态的,排序即可。之后就可以使用lower_bound去找有多少个点满足条件,维护有序表的前缀和就可得解。
除了点A所在子树外,要沿着父节点向上爬,对路径上的每个节点及该节点的另一个子树求解,向上爬的过程中H是单调递减的。

思路是对的,结果维护有序表的时候没想清楚,用了动态开点的线段树,结果时间和空间都炸了。

下次出思路以后要想清楚需要维护的信息的本质,尝试用更简单的结构和方法去优化。

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <vector>using namespace std;typedef long long lint;#define maxn (1000010)#define limit (10000000)int L[maxn], n, m;vector<lint> a[maxn], sum[maxn];struct node {    int v;    lint d;    node(int _v, lint _d) { v = _v; d = _d; }};queue<node> que;void build(int x){    while(!que.empty()) que.pop();    que.push(node(x, 0));    while(!que.empty()) {        node now = que.front(); que.pop();        a[x].push_back(now.d);        int y = now.v;        if((y<<1) <= n && now.d + L[y<<1] <= limit) {            que.push(node(y<<1, now.d + L[y<<1]));        }        if((y<<1|1) <= n && now.d + L[y<<1|1] <= limit) {            que.push(node(y<<1|1, now.d + L[y<<1|1]));        }    }    sort(a[x].begin(), a[x].end());    for(int i = 0, sz = a[x].size(); i < sz; i++) {        sum[x].push_back(a[x][i]);        if(i > 0) sum[x][i] += sum[x][i-1];    }}lint sol(int x, int k){    //printf("x = %d, k = %d\n", x, k);    lint ans = 0;    int p = lower_bound(a[x].begin(), a[x].end(), k) - a[x].begin();    if(p == a[x].size() || a[x][p] > k) p--;    if(p >= 0)        ans += (lint)k * (p + 1) - sum[x][p];    //printf("ans0 = %lld\n", ans);    while(x >> 1) {        k -= L[x];        if(k <= 0) break;        ans += k;        int y = x ^ 1;        p = lower_bound(a[y].begin(), a[y].end(), k - L[y]) - a[y].begin();        if(p == a[y].size() || a[y][p] > k - L[y]) p--;        if(p >= 0)            ans += (lint)(k - L[y]) * (p + 1) - sum[y][p];        //printf("ans = %lld\n", ans);        x >>= 1;    }    return ans;}int main(){    cin >> n >> m;    for(int i = 2; i <= n; i++) {        scanf("%d", &L[i]);    }    for(int i = 1; i <= n; i++) {        build(i);    }    for(int i = 0, A, H; i < m; i++) {        scanf("%d%d", &A, &H);        printf("%I64d\n", sol(A, H));    }    return 0;}
阅读全文
0 0
原创粉丝点击