标签:-- efi main empty namespace tor ace printf pre
T1:LCA
Code(倍增):
1 #include<iostream> 2 #include<cmath> 3 #include<cstdio> 4 #include<cstdlib> 5 #include<cstring> 6 #include<vector> 7 #include<queue> 8 #include<algorithm> 9 using namespace std; 10 vector<int>g[500005]; 11 queue<int>q; 12 const int maxpow=30; 13 int fa[40][500005]={0},dep[500005]={0}; 14 int n,p,rt,x,y; 15 bool vis[500005]={0}; 16 void bfs(int u) 17 { 18 vis[u]=true;q.push(u); 19 while(!q.empty()) 20 { 21 u=q.front(); 22 for (int i=0;i<g[u].size();i++) 23 { 24 int v=g[u][i]; 25 if (!vis[v]){dep[v]=dep[u]+1;q.push(v);} 26 } 27 q.pop(); 28 } 29 } 30 void dup() 31 { 32 for (int j=1;j<=maxpow;j++) 33 for (int i=1;i<=n;i++) 34 fa[j][i]=fa[j-1][fa[j-1][i]]; 35 } 36 int lca(int u,int v) 37 { 38 if (dep[u]<dep[v]) swap(u,v); 39 int dif=dep[u]-dep[v]; 40 for (int i=0;i<maxpow;i++) if ((1<<i)&dif) u=fa[i][u]; 41 if (u==v) return u; 42 for (int i=maxpow-1;i>=0;i--) 43 if (fa[i][u]!=fa[i][v]) {u=fa[i][u];v=fa[i][v];} 44 u=fa[0][u];return u; 45 } 46 int main() 47 { 48 scanf("%d%d",&n,&p); 49 for(int i=1;i<=n;i++) g[i].clear(); 50 for(int i=1;i<n;i++) 51 { 52 scanf("%d%d",&x,&y);g[x].push_back(y);fa[0][y]=x; 53 if (!fa[0][x]) rt=x; 54 } 55 dep[rt]=1;bfs(rt);dup(); 56 for (int k=1;k<=p;k++) 57 { 58 scanf("%d%d",&x,&y); 59 printf("%d\n",lca(x,y)); 60 } 61 return 0; 62 }
Code:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define Mx 500005 5 using namespace std; 6 struct edge{int to,next;}e[1500005]; 7 int h[Mx],q[Mx],f[Mx],a[Mx],cnt=0,n,m,c,b; 8 bool r[Mx]; 9 inline void ins(int *h,int x,int y){e[++cnt].to=y;e[cnt].next=h[x];h[x]=cnt;} 10 inline int ff(int x){return f[x]?f[x]=ff(f[x]):x;} 11 int tarjan(int u){ 12 for (int i=h[u];i;i=e[i].next){tarjan(e[i].to);f[e[i].to]=u;} 13 for (int i=q[u];i;i=e[i].next) 14 if(a[e[i].to]) a[e[i].to]=ff(a[e[i].to]); 15 else a[e[i].to]=u; 16 17 } 18 int main() 19 { 20 scanf("%d%d",&n,&m); 21 for(int i=1;i<n;i++){scanf("%d%d",&c,&b);ins(h,c,b);r[b]=1;} 22 for(int i=0;i<m;i++){scanf("%d%d",&c,&b);ins(q,c,i);ins(q,b,i);} 23 for(int i=1;i<=n;i++)if(!r[i]){tarjan(i);break;} 24 for(int i=0;i<m;i++)printf("%d\n",a[i]); 25 return 0; 26 }
标签:-- efi main empty namespace tor ace printf pre
原文地址:http://www.cnblogs.com/codingutopia/p/2017summer_day8.html