1. 首页
  2. 树状数组

UVALive 7649 Performance Review (树状数组)

题意:~

思路:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
template <class T> inline bool scan_d(T &ret) {char c; int sgn;if(c=getchar(),c==EOF) return 0;while(c!='-'&&(c<'0'||c>'9')) c=getchar(); sgn=(c=='-')?-1:1;ret=(c=='-')?0:(c-'0'); while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0'); ret*=sgn;return 1;}
int n;
const int N = 100050;
struct mmp {
    int v, next;
} edge[N];
int head[N], tot;
void add(int u, int v)
{
    edge[tot] = {v, head[u]};
    head[u] = tot++;
}
LL val[N];
LL ans[N], sum[N];
int lev[N];

void init()
{
    memset(head, -1, sizeof(head));
    tot = 0;
    memset(ans, 0, sizeof(ans));
    memset(sum, 0, sizeof(sum));
}

void update(int x, LL val)
{
    for(int i = x; i < N; i += i & (-i))
    {
        sum[i] += val;
    }
}

LL query(int x)
{
    LL res = 0;
    for(int i = x; i > 0; i -= i & (-i))
    {
        res += sum[i];
    }
    return res;
}

void dfs(int u)
{
    LL pre = query(lev[u] - 1);
    update(lev[u], val[u]);
    for(int i = head[u]; i != -1; i = edge[i].next)
    {
        int v = edge[i].v;
        dfs(v);
    }
    ans[u] = query(lev[u] - 1) - pre;
}

int main()
{
    while(~scanf("%d", &n))
    {
        init();
        int u, k, w;
        int rt = 0;
        for(int i = 1; i <= n; ++i)
        {
            scan_d(u), scan_d(k), scan_d(w);
            lev[i] = k;
            val[i] = w;
            if(u == -1) rt = i;
            else add(u, i);
        }
        dfs(rt);
        for(int i = 1; i <= n; ++i) printf("%lld\n", ans[i]);
    }
    return 0;
}

 

评分 0, 满分 5 星
0
0
看完收藏一下,下次也能找得到
  • 版权声明:本文基于《知识共享署名-相同方式共享 3.0 中国大陆许可协议》发布,转载请遵循本协议
  • 文章链接:http://www.carlstedt.cn/archives/1428 (转载时请注明本文出处及文章链接)
上一篇:
:下一篇

发表评论

gravatar

快来吐槽一下吧!

  1. .01 4:06
  2. .02 1:47
  3. .03 3:39
  4. .04 1:40