很明显,这题是一个动态的点分治,二进制一位一位的拆开来做,
我们记录每个点到它每轮的点分治的重心,
当前的二进制位更改后,只需要在它每轮分治所属的区域内进行操作,更改当前区域内的数据,计算答案,在去上一个区域,
我们在点分治的时候,只考虑经过了当前重心的路径,所有每轮的区域处理也只考虑除了被修改点所属的重心的儿子的所有儿子的点外的所有点,不停的往上处理即可
复杂度: O(nlog(n)) ;
有点小码农,祝君好运!
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define efo(i,q,A) for(int i=A[q];i;i=B[i][0])
#define aqs a[q].s
#define scQ sc[Q]
#define scF sc[FA]
using namespace std;
typedef long long LL;
const int N=30050,maxlongint=2147483640,M=15;
int read(int &n)
{
char ch=' ';int q=0,w=1;n=0;
for(;(ch!='-')&&((ch<'0')||(ch>'9'));ch=getchar());
if(ch=='-')w=-1,ch=getchar();
for(;ch>='0' && ch<='9';ch=getchar())q=q*10+ch-48;n=q*w;return n;
}
int n,m;
struct qqww
{int fa,FA,c,s[M+1][2][2];}a[N];
int si[N],dis[M+1][N],er[M+1];
int sc[N*5][M+1][2][2],sc0;
int B[N*2][3],A[N],B0=1,b[N],ce,ce1;
bool z[N];
LL ans[M+1],ANS;
void join(int q,int w,int e)
{
B[++B0][0]=A[q],A[q]=B0,B[B0][1]=w,B[B0][2]=e;
B[++B0][0]=A[w],A[w]=B0,B[B0][1]=q,B[B0][2]=e;
}
int findc(int q,int fa,int all)
{
int mx=0;si[q]=1;
efo(i,q,A)if(!z[B[i][1]]&&fa!=B[i][1])si[q]+=findc(B[i][1],q,all),mx=max(si[B[i][1]],mx);
mx=max(mx,all-si[q]);if(mx<ce1)ce1=mx,ce=q;return si[q];
}
void dfs(int q,int e,int fa,int c,int Q)
{
dis[c][q]=e;
fo(i,1,M)
{
scQ[i][(b[q]&er[i])!=0][1]+=e;
scQ[i][(b[q]&er[i])!=0][0]++;
}
efo(i,q,A)if(B[i][1]!=fa&&!z[B[i][1]])dfs(B[i][1],e+B[i][2],q,c,Q);
}
void divide(int q,int fa,int FA,int c,int alln)
{
int w=q;
ce1=maxlongint,findc(q,0,alln);q=ce;
z[q]=1;a[q].c=c;a[q].fa=fa;a[q].FA=FA;
fo(i,1,M)aqs[i][(b[q]&er[i])!=0][0]++;
int FFF=sc0;
efo(i,q,A)if(!z[w=B[i][1]])
{
dfs(w,B[i][2],q,c,FA=++sc0);
fo(j,1,M)
fo(k,0,1)
{
ans[j]+=(LL)scF[j][!k][1]*aqs[j][k][0]+(LL)aqs[j][k][1]*scF[j][!k][0];
aqs[j][k][0]+=scF[j][k][0],aqs[j][k][1]+=scF[j][k][1];
}
}
efo(i,q,A)if(!z[w=B[i][1]])divide(w,q,++FFF,c+1,si[w]);
}
void gup(int q,int I,int FA,int J,int Q)
{
while(q)
{
int e=dis[a[q].c][Q],c=a[q].c;
ans[I]-=aqs[I][!J][1]-scF[I][!J][1]+(LL)e*(aqs[I][!J][0]-scF[I][!J][0]);
aqs[I][J][0]--,aqs[I][J][1]-=e;scF[I][J][0]--,scF[I][J][1]-=e;
aqs[I][!J][0]++,aqs[I][!J][1]+=e;scF[I][!J][0]++,scF[I][!J][1]+=e;
ans[I]+=aqs[I][J][1]-scF[I][J][1]+(LL)e*(aqs[I][J][0]-scF[I][J][0]);
FA=a[q].FA;q=a[q].fa;
}
}
int main()
{
er[1]=1;
fo(i,2,M)er[i]=er[i-1]<<1;
int q,w,e,_;
read(n);
fo(i,1,n)read(b[i]);
fo(i,1,n-1)read(q),read(w),read(e),join(q,w,e);
divide(1,0,1,0,n);
read(_);
memset(a[0].s,0,sizeof(a[0].s));
while(_--)
{
read(q),read(e);
fo(i,1,M)if((e&er[i])!=(b[q]&er[i]))gup(q,i,0,(b[q]&er[i])!=0,q);
b[q]=e;ANS=0;
fo(i,1,M)ANS+=ans[i]*er[i];
printf("%lld\n",ANS);
}
return 0;
}