题目描述 Description
小机房有棵焕狗种的树,树上有N个节点,节点标号为0到N-1,有两只虫子名叫飘狗和大吉狗,分居在两个不同的节点上。有一天,他们想爬到一个节点上去搞基,但是作为两只虫子,他们不想花费太多精力。已知从某个节点爬到其父亲节点要花费 c 的能量(从父亲节点爬到此节点也相同),他们想找出一条花费精力最短的路,以使得搞基的时候精力旺盛,他们找到你要你设计一个程序来找到这条路,要求你告诉他们最少需要花费多少精力
输入描述 Input Description
第一行一个n,接下来n-1行每一行有三个整数u,v, c 。表示节点 u 爬到节点 v 需要花费 c 的精力。
第n+1行有一个整数m表示有m次询问。接下来m行每一行有两个整数 u ,v 表示两只虫子所在的节点
输出描述 Output Description
一共有m行,每一行一个整数,表示对于该次询问所得出的最短距离。
样例输入 Sample Input
3
1 0 1
2 0 1
3
1 0
2 0
1 2
样例输出 Sample Output
1
1
2
数据范围及提示 Data Size & Hint
1<=n<=50000, 1<=m<=75000, 0<=c<=1000
题目要求两点间简单路径长度,树剖秒a~
下午学fft,数论虐我,感觉好颓,选择来打lct。。。
makeroot之后x没有左儿子,在access y之后主splay仅维护了x->lca(x,y)->y之间的信息。
#include<bits/stdc++.h>
using namespace std;
#define Inc(i,L,R) for(register int i=(L);i<=(R);++i)
#define Red(j,R,L) for(register int j=(R);j>=(L);--j)
const int N = 2e5+10;
struct Inform{
int num,sum;
}a[N];
struct Splay{
bool rev[N];
int p[N],ch[N][2];
#define Ls(v) ch[v][0]
#define rs(v) ch[v][1]
bool is_root(int x){
return (Ls(p[x])^x)&&(rs(p[x])^x);
}
inline void pushdown(int x){
if(rev[x]){
rev[Ls(x)]^=1,rev[rs(x)]^=1;
swap(Ls(x),rs(x));
rev[x]=0;
}
}
inline void maintain(int x){
a[x].sum=a[Ls(x)].sum+a[rs(x)].sum+a[x].num;
}
inline void rot(int x){
int f=p[x],gf=p[f],type=rs(f)==x,son=ch[x][!type];
if(!is_root(f))ch[gf][rs(gf)==f]=x;p[x]=gf;
ch[p[son]=f][type]=son,maintain(f);
ch[p[f]=x][!type]=f,maintain(x);
}
int top,stk[N];
inline void splay(int x){
stk[++top]=x;
if(!is_root(x))for(int i=x;!is_root(i);i=p[i])stk[++top]=p[i];
while(top)pushdown(stk[top--]);
while(!is_root(x)){
if(is_root(p[x]))return rot(x),void();
if((rs(p[p[x]])==p[x])==(rs(p[x])==x))rot(p[x]);
rot(x);
}
}
};
struct LCT{
Splay sp;
inline int access(int x){
int lastx=0;
while(x){
sp.splay(x);
sp.rs(x)=lastx;
sp.maintain(x);
lastx=x;
x=sp.p[x];
}
return lastx;
}
inline void make_root(int x){
access(x);
sp.splay(x);
sp.rev[x]^=1;
}
inline void Link(int x,int y){
make_root(x),sp.p[x]=y;
}
inline void work(int x,int y){
make_root(x);
access(y);
sp.splay(y);
cout<<a[y].sum<<"\n";
}
}lct;
int n,m;
inline void init(){
scanf("%d",&n);
Inc(i,1,n-1){
int x,y,w;scanf("%d%d%d",&x,&y,&w);
a[i+n].num=a[i+n].sum=w;
lct.Link(x+1,i+n);
lct.Link(i+n,y+1);
}
}
inline void solv(){
scanf("%d",&m);
while(m--){
int x,y;scanf("%d%d",&x,&y);
lct.work(x+1,y+1);
}
}
int main(){
init();
solv();
return 0;
}