bzoj3732 Network

传送门

分析

kruskal重构树上倍增求LCA

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<ctime>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
const int LOG = 20;
struct node {
    int x,y,a;
};
node d[400100];
int fa[400100],cnt,val[400100],pa[LOG+3][400100],dep[400100];
vector<int>v[400100];
inline bool cmp(const node a,const node b){
    return a.a<b.a;
}
inline void dfs(int x){
      for(int i=0;i<v[x].size();i++){
            dep[v[x][i]]=dep[x]+1;
            dfs(v[x][i]);
            pa[0][v[x][i]]=x;
            pa[0][v[x][i]]=x;
      }
}
inline int lca(int x,int y){
      if(dep[x]>dep[y])swap(x,y);
      for(int i=LOG;i>=0;i--)
         if(dep[y]-dep[x]>=(1<<i))
             y=pa[i][y];
      if(x==y)return val[x];
      for(int i=LOG;i>=0;i--)
         if(pa[i][x]!=pa[i][y])
             x=pa[i][x],y=pa[i][y];
      return val[pa[0][x]];
}
inline int sf(int x){return fa[x]==x?x:fa[x]=sf(fa[x]);}
int main(){
    int n,m,i,j,k=0,q;
    scanf("%d%d%d",&n,&m,&q);
    cnt=n;
    for(i=1;i<=n+m;i++)fa[i]=i;
    for(i=1;i<=m;i++)
      scanf("%d%d%d",&d[i].x,&d[i].y,&d[i].a);
    sort(d+1,d+m+1,cmp);
    for(i=1;i<=m;i++){
      if(sf(d[i].x)!=sf(d[i].y)){
          int xx=sf(d[i].x),yy=sf(d[i].y);
          fa[xx]=++cnt;
          fa[yy]=cnt;
          val[cnt]=d[i].a;
          v[cnt].push_back(xx);
          v[cnt].push_back(yy);
      }
      if(k==n-1)break;
    }
    dfs(cnt);
    for(i=1;i<=LOG;i++)
      for(j=1;j<=cnt;j++)
        pa[i][j]=pa[i-1][pa[i-1][j]];
    for(i=1;i<=q;i++){
      int x,y;
      scanf("%d%d",&x,&y);
      printf("%d\n",lca(x,y));
    }
    return 0;
}
posted @ 2019-01-28 09:34  水题收割者  阅读(145)  评论(0编辑  收藏  举报