您的位置:首页 > 编程语言 > Go语言

HDU 3966 Aragorn's Story

2016-07-28 18:59 471 查看

题目分析

树链剖分基础题。2种操作:第一种:询问节点C的敌人数。另一种为改变a到b的路径上所有节点的敌人数。

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 50010;
#define mid (L+R)/2
#define lson o<<1, L, mid
#define rson o<<1|1, mid+1, R
int sum[maxn<<2],add[maxn<<2],num[maxn];

void pushdown(int o,int L,int R){
if(add[o]){
sum[o<<1] += add[o]*(mid-L+1);
sum[o<<1|1] += add[o]*(R-mid);
add[o<<1] += add[o];
add[o<<1|1] += add[o];
add[o] = 0;
}
}

void update(int o,int L,int R,int l,int r,int val){
if(l <= L && R <= r){
add[o] += val;
sum[o] += val*(R-L+1);
return ;
}
pushdown(o, L, R);
if(l <= mid) update(lson, l, r, val);
if(r > mid) update(rson, l, r, val);
sum[o] = sum[o<<1] + sum[o<<1|1];
}

int query(int o,int L,int R,int p){
if(L == R) return sum[o];
pushdown(o, L, R);
if(p <= mid) return query(lson, p);
else return query(rson, p);
}

int siz[maxn],dep[maxn],fa[maxn],son[maxn],top[maxn],w[maxn],head[maxn],cnt,tot;

struct Edge{
int to,next;
}e[maxn<<1];

void addedge(int from,int to){
e[cnt].to = to;
e[cnt].next = head[from];
head[from] = cnt++;
}

void dfs1(int now){
son[now] = 0;
siz[now] = 1;
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != fa[now]){
dep[v] = dep[now]+1;
fa[v] = now;
dfs1(v);
if(siz[son[now]] < siz[v]) son[now] = v;
siz[now] += siz[v];
}
}
}

void dfs2(int now,int tp){
w[now] = ++tot;
top[now] = tp;
if(son[now]) dfs2(son[now], top[now]);
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != fa[now] && v != son[now])
dfs2(v, v);
}
}

void change(int a,int b,int c){
int f1 = top[a],f2 = top[b];
while(f1 != f2){
if(dep[f1] < dep[f2]){
swap(f1, f2);
swap(a, b);
}
update(1, 1, tot, w[f1], w[a], c);
a = fa[f1];
f1 = top[a];
}
if(dep[a] > dep[b])
swap(a, b);
update(1, 1, tot, w[a], w[b], c);
}

void init(){
tot = cnt = 0;
memset(head, -1, sizeof(head));
memset(siz, 0, sizeof(siz));
memset(sum, 0, sizeof(sum));
memset(add, 0, sizeof(add));
memset(dep, 0, sizeof(dep));
memset(fa, 0 ,sizeof(fa));
memset(son, 0, sizeof(son));
}

int main(){
int N,M,P;
while(scanf("%d%d%d", &N, &M, &P) != EOF){
init();
for(int i = 1; i <= N; i++)
scanf("%d", &num[i]);
int a,b,c;
for(int i = 1; i <= M; i++){
scanf("%d%d", &a, &b);
addedge(a, b);
addedge(b, a);
}
dfs1(1);
dfs2(1, 1);
for(int i = 1; i <= N; i++) update(1, 1, tot, w[i], w[i], num[i]);
char op[5];
while(P--){
scanf("%s", op);
if(op[0] == 'I'){
scanf("%d%d%d", &a, &b, &c);
change(a, b, c);
}
else if(op[0] == 'D'){
scanf("%d%d%d", &a, &b, &c);
change(a, b, -c);
}
else{
scanf("%d", &a);
printf("%d\n", query(1, 1, tot, w[a]));
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: