[BZOJ1602][Usaco2008 Oct]牧场行走(LCA)
来源:互联网 发布:部落战争mac电脑版 编辑:程序博客网 时间:2024/06/05 02:17
题目描述
传送门
题解
一眼链剖。
维护边实在不想写。
lca水过。
dis表示一个点到根的距离,则两点之间距离可以表示为dis[x]+dis[y]-2*dis[lca(x,y)]
代码
#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int max_n=1e4+5;const int max_e=max_n*2;const int sz=10;int n,q,x,y,z,ans;int tot,point[max_n],next[max_e],v[max_e],c[max_e];int dis[max_n],h[max_n];int mi[sz],f[max_n][sz];inline void addedge(int x,int y,int z){ ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z; ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; c[tot]=z;} inline void dfs(int x,int fa,int dist,int dep){ dis[x]=dis[fa]+dist; h[x]=dep; for (int i=1;i<sz;++i){ if (h[x]-mi[i]<1) break; f[x][i]=f[f[x][i-1]][i-1]; } for (int i=point[x];i;i=next[i]) if (v[i]!=fa){ f[v[i]][0]=x; dfs(v[i],x,c[i],dep+1); }}inline int lca(int x,int y){ if (h[x]<h[y]) swap(x,y); int k=h[x]-h[y]; for (int i=0;i<sz;++i) if ((k>>i)&1) x=f[x][i]; if (x==y) return x; for (int i=sz-1;i>=0;--i) if (f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i]; return f[x][0];}int main(){ scanf("%d%d",&n,&q); for (int i=1;i<n;++i){ scanf("%d%d%d",&x,&y,&z); addedge(x,y,z); } mi[0]=1; for (int i=1;i<sz;++i) mi[i]=mi[i-1]*2; dfs(1,0,0,1); for (int i=1;i<=q;++i){ scanf("%d%d",&x,&y); z=lca(x,y); ans=dis[x]+dis[y]-2*dis[z]; printf("%d\n",ans); } }
总结
倍增很久没写了快忘了啊
再多打几遍吧。
0 0
- [BZOJ1602][Usaco2008 Oct]牧场行走(LCA)
- bzoj1602[Usaco2008 Oct]牧场行走(lca模版)
- [Bzoj1602][Usaco2008 Oct]牧场行走
- bzoj1602 [Usaco2008 Oct]牧场行走
- [BZOJ1602][Usaco2008 Oct]牧场行走
- bzoj1602 [Usaco2008 Oct]牧场行走
- BZOJ1602: [Usaco2008 Oct]牧场行走
- BZOJ1602: [Usaco2008 Oct]牧场行走
- bzoj1602 [Usaco2008 Oct]牧场行走
- BZOJ1602 [Usaco2008 Oct]牧场行走
- bzoj1602: [Usaco2008 Oct]牧场行走 暴力dfs
- 【bzoj1602】【Usaco2008 Oct】牧场行走 (暴力) 题解&代码
- 【bzoj1602】牧场行走 lca
- bzoj 1602 [Usaco2008 Oct]牧场行走(LCA模板)
- bzoj 1602: [Usaco2008 Oct]牧场行走(暴力LCA)
- 1602: [Usaco2008 Oct]牧场行走|Lca
- [Usaco2008 Oct]牧场行走
- BZOJ 1602 Usaco2008 Oct 牧场行走 倍增LCA
- Android 操作数据库Sqlite,数据写入到SD卡里面
- Spring事务异常回滚,捕获异常不抛出就不会回滚
- Problem H: 今年第几天?
- 不用加减乘除做加法
- Android 加载图片传到另一个页面 关于回调
- [BZOJ1602][Usaco2008 Oct]牧场行走(LCA)
- Redis 集群的合纵与连横
- SDAU课程练习2 1019
- DFS求起点到终点最短路径,手动输入地图,5行4列,地图如下,起点(1,1)终点(4,3) 1是障碍 0是通路
- hdoj 素数回文 1431 (模拟)
- E Cheerleaders (UVA 11806)
- 第五周项目22-分数类的雏形
- [JAVA]有关比较器(Comparator接口)的用法及对象数组排序问题
- TCP建立连接和断开连接过程