标签:result pair ble push 倍增 usaco highlight first define
一棵树,询问两点间距离.
倍增.
方向没用.
没有然后了.
/************************************************************** Problem: 3364 User: BeiYu Language: C++ Result: Accepted Time:400 ms Memory:11556 kb ****************************************************************/ #include<cstdio> #include<utility> #include<vector> #include<iostream> using namespace std; #define mpr make_pair typedef pair< int,int > pr; const int N = 40005; const int M = 20; int n,m,k; vector<pr> h[N]; bool b[N]; int pow2[M],d[N]; int f[N][M],g[N][M]; inline int in(int x=0,char ch=getchar()){ while(ch>‘9‘ || ch<‘0‘) ch=getchar(); while(ch>=‘0‘ && ch<=‘9‘) x=(x<<3)+(x<<1)+ch-‘0‘,ch=getchar();return x; } void DFS(int u,int fa){ b[u]=1,d[u]=d[fa]+1; for(int i=0,v;i<h[u].size();i++) if((v=h[u][i].first)!=fa){ DFS(v,u),f[v][0]=u,g[v][0]=h[u][i].second; } } void work(){ pow2[0]=1;for(int i=1;i<M;i++) pow2[i]=pow2[i-1]<<1; for(int j=1;j<M;j++) for(int i=1;i<=n;i++) f[i][j]=f[f[i][j-1]][j-1],g[i][j]=g[i][j-1]+g[f[i][j-1]][j-1]; } int Dis(int u,int v){ if(d[u]<d[v]) swap(u,v); int l=d[u]-d[v],res=0; for(int i=0;i<M;i++) if(l&pow2[i]) res+=g[u][i],u=f[u][i]; if(u==v) return res; for(int i=M-1;~i;--i){ if(f[u][i]!=f[v][i]) res+=g[u][i]+g[v][i],u=f[u][i],v=f[v][i]; }return g[u][0]+g[v][0]+res; } int main(){ n=in(),m=in(); for(int i=1,u,v,w;i<=m;i++) u=in(),v=in(),w=in(),h[u].push_back(mpr(v,w)),h[v].push_back(mpr(u,w)); for(int i=1;i<=n;i++) if(!b[i]) DFS(i,i); work(); for(k=in();k--;){ int u=in(),v=in(); printf("%d\n",Dis(u,v)); }return 0; }
BZOJ 3364: [Usaco2004 Feb]Distance Queries 距离咨询
标签:result pair ble push 倍增 usaco highlight first define
原文地址:http://www.cnblogs.com/beiyuoi/p/6049520.html