bzoj 1602

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 100000 
using namespace std;
int n,m;
int key[N],ch[N][3],fa[N],rev[N],st[N],map[1003][1003];
int isroot(int x)
{
  return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;
}
void pushdown(int x)
{
  if (!rev[x]||!x) return;
  rev[ch[x][0]]^=1;
  rev[ch[x][1]]^=1;
  swap(ch[x][0],ch[x][1]);
  rev[x]=0;
}
int get(int x)
{
  return ch[fa[x]][1]==x;
}
void rotate(int x)
{
  int y=fa[x]; int z=fa[y]; int which=get(x);
  if (!isroot(y))
   ch[z][ch[z][1]==y]=x;
  ch[y][which]=ch[x][which^1]; fa[ch[y][which]]=y;
  ch[x][which^1]=y; fa[y]=x; fa[x]=z;
}
void splay(int x)
{
  int top=0; st[++top]=x;
  for (int i=x;!isroot(i);i=fa[i])
   st[++top]=fa[x];
  for (int i=top;i>=1;i--) pushdown(st[i]);
  while (!isroot(x))
  {
   int y=fa[x];
   if (!isroot(y))
    rotate(get(x)==get(y)?y:x);
   rotate(x);
  }
}
void access(int x)
{
  int t=0;
  while (x)
  {
    splay(x);
    ch[x][1]=t;
    t=x; x=fa[x];
  }
}
void rever(int x)
{
  access(x); splay(x); rev[x]^=1;
}
void link(int x,int y,int z)
{
  rever(x); access(y); splay(y); fa[y]=x; 
}
int  access1(int x)
{
  int t=0; int ans=0;
  while (x)
  {
    splay(x);
    ch[x][1]=t;
    if (t)  ans+=map[x][t];
    t=x; x=fa[x];
  }
  return ans;
}
int main()
{
  scanf("%d%d",&n,&m);
  for (int i=1;i<=n-1;i++)
   {
   	int x,y,z; scanf("%d%d%d",&x,&y,&z);
   	if (x>y)  swap(x,y);
   	link(x,y,z);
   	map[x][y]=map[y][x]=z;
   }
  for (int i=1;i<=m;i++)
   {
     int x,y; scanf("%d%d",&x,&y);
     rever(x); 
     printf("%d\n",access1(y));
   }
} 

你可能感兴趣的:(bzoj 1602)