给出一棵二叉树,节点i与2*i和2*i+1相连,i的范围是1~10^18,每一条边有一个权值w(0~10^9),给出q(1~1000)个操作,操作有两种,1:将u-v所有边的权值加上w。2:询问u-v所有边的总的权值。
首先分析u-v,这使我们很容易想到LCA,但是数据范围太大,所以利用二叉树的性质:i的父亲为(i>>1),再加上LCA的思想,就可以做出框架,但还是由于数据范围太大,所以只能用map储存各个边的值(map[i]表示i-(i>>1)的值)。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#define LL long long
using namespace std;
map<LL,LL>s;
LL u,v,w;
void update(LL u,LL v,LL w){
while(u != v){
if(u > v){
s[u] += w;
u >>= 1;
}
if(u < v){
s[v] += w;
v >>= 1;
}
}
}
LL query(LL u,LL v){
LL res = 0;
while(u != v){
if(u > v){
res += s[u];
u >>= 1;
}
if(u < v){
res += s[v];
v >>= 1;
}
}
return res;
}
int main(){
int q,op;
scanf("%d",&q);
for(int i = 1;i <= q;++i){
cin>>op>>u>>v;
if(op == 1){
cin>>w;
update(u,v,w);
}
else{
cout<<query(u,v)<<endl;
}
}
return 0;
}