CodeForces 696A Lorenzo Von Matterhorn (LCA + map)

时间:2023-03-09 14:21:24
CodeForces 696A Lorenzo Von Matterhorn (LCA + map)

  方法:求出最近公共祖先,使用map给他们计数,注意深度的求法。

  代码如下:

#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
using namespace std;
#define LL long long
map<LL,LL> sum;
int Get_Deep(LL x)
{
for(int i = ; i < ; i++)
{
if((1LL<<i)<=x && (1LL<<(i+))>x) return i+;
}
return ;
}
void F_LCA(LL x,LL y,LL w)
{
// cout<<"deep "<<x<<" "<<Get_Deep(x)<<endl;
// cout<<"deep "<<y<<" "<<Get_Deep(y)<<endl;
while(Get_Deep(x) > Get_Deep(y))
{
sum[x] += w;
x /= ;
}
while(Get_Deep(y) > Get_Deep(x))
{
sum[y] += w;
y /= ;
}
while(x != y)
{
sum[x] += w;
sum[y] += w;
x /= ;
y /= ;
}
}
LL G_LCA(LL x,LL y)
{
LL ans = ;
while(Get_Deep(x) > Get_Deep(y))
{
ans += sum[x];
x /= ;
}
while(Get_Deep(y) > Get_Deep(x))
{
ans += sum[y];
y /= ;
}
while(x != y)
{
ans += sum[x];
ans += sum[y];
x /= ;
y /= ;
}
return ans;
}
int main()
{
int q,op;
LL u,v,w;
cin>>q;
sum.clear();
while(q--)
{
cin>>op;
if(op == )
{
cin>>u>>v>>w;
F_LCA(u,v,w);
}
else
{
cin>>u>>v;
cout<<G_LCA(u,v)<<endl;
}
}
return ;
}