BZOJ1602: [Usaco2008 Oct]牧场行走
来源:互联网 发布:ipad换壁纸软件 编辑:程序博客网 时间:2024/05/22 03:46
题目传送门
题解:一个简单LCA即可 记录一下根到每个节点的距离
然后对于每个询问(a,b)的答案就是根到a的距离+根到b的距离-2*根到LCA(a,b)的距离
#include<bits/stdc++.h>#define ll long longconst int INF = 0x7fffffff;const double eps = 1e-5;const int maxn = 1e3 + 5;using namespace std;int read(){int x = 0 , f = 1; char ch = getchar();while(ch<'0'||ch>'9') {if(ch=='-')f*=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+(ch-'0');ch=getchar();}return x * f;}int n,q;int cnt,to[maxn<<1],nxt[maxn<<1],c[maxn<<1],head[maxn];int deep[maxn],fa[maxn][18],dis[maxn],vis[maxn];void add(int u,int v,int w){to[++cnt] = v ; nxt[cnt] = head[u] ; head[u] = cnt; c[cnt] = w;to[++cnt] = u ; nxt[cnt] = head[v] ; head[v] = cnt; c[cnt] = w;}void dfs(int x,int f){vis[x]=1;for(int i = 1; i <= 9; i++){if(deep[x]<(1<<i)) break;fa[x][i] = fa[fa[x][i-1]][i-1];}for(int i = head[x]; i; i = nxt[i]){if(to[i] != f){deep[to[i]] = deep[x]+1;dis[to[i]] = dis[x] + c[i];fa[to[i]][0]=x;dfs(to[i],x);}}}int LCA(int a,int b){if(deep[b] > deep[a]) swap(a,b);int t = deep[a] - deep[b];for(int i = 0 ; i <= 9 ; i++)if(t&(1<<i)) a = fa[a][i];for(int i = 0 ; i <= 9 ; i++){while(fa[a][i]!=fa[b][i])a=fa[a][i],b=fa[b][i];}if(a==b) return a;else return fa[a][0];}int main(){n = read() , q = read();for(int i = 1 ; i < n ; i++){int a = read() , b = read() , c = read();add(a,b,c);}dfs(1,0);for(int i = 1 ; i <= q ; i++){int a = read(), b =read();printf("%d\n",dis[a]+dis[b]-(dis[LCA(a,b)]<<1));}return 0;}
阅读全文
0 0
- [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]牧场行走(LCA)
- bzoj1602: [Usaco2008 Oct]牧场行走 暴力dfs
- bzoj1602[Usaco2008 Oct]牧场行走(lca模版)
- 【bzoj1602】【Usaco2008 Oct】牧场行走 (暴力) 题解&代码
- [Usaco2008 Oct]牧场行走
- BZOJ [Usaco2008 Oct]牧场行走
- [BZOJ602][Usaco2008 Oct]牧场行走
- BZOJ 1602: [Usaco2008 Oct]牧场行走
- BZOJ 1602 [Usaco2008 Oct]牧场行走 dfs
- 1602: [Usaco2008 Oct]牧场行走|Lca
- java基础代码练习
- 最长回文子串——Manacher 算法
- 怎么修改列的定义
- 如何解决SpringBoot与ODataJClient版本冲突的问题?
- 英雄联盟开发例子生动形象地为你讲解StrategyPattern------策略模式
- BZOJ1602: [Usaco2008 Oct]牧场行走
- 实训的第七天 加油
- HDU Text Reverse/1.2
- 排序算法之选择排序
- 2017新开的几个坑
- Android四种第三方登录的方法
- Webrtc delay-base-bwe代码分析(3): OveruseEstimator模块
- You do not have permission to get URL ‘/’ from this server解决方案
- 计算机网络自顶向下方法学习笔记