虚树(建树):
所谓虚树,其实就是将原树缩小,即保留适当的重要节点(我们称为key point),对于此类问题,显然只有key point影响答案,因此我们只需对这些key point进行操作。
适用范围:数据很大,关键节点较少
虚树考得还是其它算法应用,只是套了一层虚树的壳,因此,我们只需明确如何处理虚树即可。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e6+10;
#define FOR(i,L,R) for(register int i=(L);i<=(R);++i)
#define REP(j,R,L) for(register int j=(R);j>=(L);--j)
int n;
struct Graph{//处理最初图,求lca
vector<int>G[N];
int cnt,xu[N],dep[N],p[N][27];
inline int lca(int x,int y){
if(dep[x]<dep[y])swap(x,y);
REP(i,log2(dep[x]),0)if(dep[x]-(1<<i)>=dep[y])x=p[x][i];
if(x==y)return y;
REP(i,log2(dep[x]),0)if(p[x][i]^p[y][i])x=p[x][i],y=p[y][i];
return p[x][0];
}
inline void ST(){
int k=log2(n);
FOR(j,1,k)FOR(i,1,n)if(~p[i][j-1])p[i][j]=p[p[i][j-1]][j-1];
}
inline void dfs(int u,int fa,int depth){
xu[u]=++cnt;
int sz=G[u].size()-1;
FOR(i,0,sz)if(G[u][i]^fa)dfs(G[u][i],p[G[u][i]][0]=u,dep[G[u][i]]=depth+1);
}
inline void init(){
memset(p,-1,sizeof(p));
scanf("%d",&n);
FOR(i,1,n-1){
int x,y;scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
}
}g;
bool cmp(int a,int b){
return g.xu[a]<g.xu[b];
}
struct Fake_Tree{//应该是这么翻译吧……
struct edge{
int to,next,w;
}a[N];//这里不用vector是因为清空很慢
int m,h[N],sig[N],flag[N];
int cnt,top,stk[N];
#define next a[p].next
#define to a[p].to
#define w a[p].w
inline void solv(){
……
FOR(i,1,m)flag[sig[i]]=0;//记得清空。。。
}
inline void add(int u,int v){
if(u==v)return ;//注意这里很重要!
a[++cnt]=(edge){v,h[u],g.dep[v]-g.dep[u]};h[u]=cnt;//因为每次维护一条树链且是单位长度,所以u和v的距离就是他们之间的深度
}
inline void init(){
scanf("%d",&m);
FOR(i,1,m)scanf("%d",sig+i);//读入key point
sort(sig+1,sig+m+1,cmp);
FOR(i,1,m)flag[sig[i]]=1;//标记
//注意有的题可以删去一些关键点
cnt=top=0;
stk[++top]=1;
FOR(i,1,m){
int now=sig[i],lca=g.lca(now,stk[top]);
while(g.dep[lca]<g.dep[stk[top-1]]){//因为是维护树链,所以可用深度判断
add(stk[top-1],stk[top]);
--top;
}add(lca,stk[top]);
stk[top]=lca;//直接覆盖,注意上面使用top-1判断
if(stk[top]!=now)stk[++top]=now;//判断稳妥一点
}while(--top)add(stk[top],stk[top+1]);//最后剩在栈里的一条链
}
}z;
int main(){
g.init();
g.dfs(1,g.p[1][0]=0,g.dep[1]=1);
g.ST();
int Case;scanf("%d",&Case);
while(Case--){
z.init();
z.solv();
}return 0;
}