HDU - 2586 How far away ?(最近公共祖先)

HDU---2586:How far away?【三种方法求LCA】 题目: HDU---2586:How far away? 题意: 给定一颗树,求任意两点之间的距离 分析: (1)倍增求LCA: 定义dp[u][x]表示u这个节点向上跳2^x步到达的节点,不包括本身,那么dp[u][0] = fa[u],dfs一遍处理出深度数组deep[u]和dp[u][0]和u到根节点的距离dis[u],求LCA(u,v)时,先使u,v位于同一深度,然后一起向上倍... 阅读详情

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this “How far is it if I want to go from house A to house B”? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path(“simple” means you can’t visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.

模板+1。
这篇博客就专门用来存板子,把倍增,tarjan,rmq树剖什么的都打一遍。

这题任意一点都能作为根,有点意思。

倍增算法:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 40005;

struct Node {
	int ch, dis;
};

vector<Node> G[maxn];
int rdis[maxn];
int fa[22][maxn], dep[maxn];

void dfs(int u, int f, int dis) {
	fa[0][u] = f;
	rdis[u] = dis;
	dep[u] = dep[f] + 1;
	// printf("~~~~%d\n",dis);
	for(int i = 0; i < G[u].size(); i++) {
		int v = G[u][i].ch;
		if(v == f) {
			continue;
		}
		dfs(v, u, dis + G[u][i].dis);
	}
}

void init(int n) {
	memset(fa, 0, sizeof(fa));
	dep[0] = 0;
	dfs(1, 0, 0);
	for(int k = 0; k + 1 < 20; k++) {
		for(int v = 1; v <= n + n; v++) {
			if(!fa[k][v]) {
				fa[k + 1][v] = 0;
			} else {
				fa[k + 1][v] = fa[k][fa[k][v]];
			}
		}
	}
}

int lca(int u, int v) {
	if(dep[u] > dep[v]) {
		swap(u, v);
	}
	for(int k = 0; k < 20; k++) {
		if((dep[v] - dep[u]) >> k & 1) {
			v = fa[k][v];
		}
	}
	if(u == v) {
		return u;
	}
	for(int k = 20 - 1; k >= 0; k--) {
		if(fa[k][u] != fa[k][v]) {
			u = fa[k][u];
			v = fa[k][v];
		}
	}
	return fa[0][u];
}

int main() {
	int t, n, m;
	scanf("%d", &t);
	while(t--) {
		scanf("%d%d", &n, &m);

		for(int i = 0; i <= n; i++) {
			G[i].clear();
		}

		int i, j, k;
		for(int c = 0; c < n - 1; c++) {
			scanf("%d%d%d", &i, &j, &k);
			G[i].push_back({j, k});
			G[j].push_back({i, k});
		}
		init(n);
		int a, b;
		while(m--) {
			scanf("%d%d", &a, &b);
			int ans = rdis[a] + rdis[b] - rdis[lca(a, b)] * 2;
			printf("%d\n", ans);
		}
	}
	return 0;
}

tarjan:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 40005;

int t, n, m;
int fa[maxn], rdis[maxn];
int x[maxn], y[maxn], z[maxn];
bool vis[maxn];

struct Node {
	int ch, dis;
};

vector<Node> G[maxn];


int find(int x) {
	return x == fa[x] ? x : fa[x] = find(fa[x]);
}

void merge(int x, int y) {
	x = find(x);
	y = find(y);
	if(x == y) return;
	fa[y] = x;
}

void init() {
	rdis[1] = 0;
	memset(vis, 0, sizeof(vis));
	memset(fa, 0, sizeof(fa));
	for(int i = 1; i <= n; i++) {
		G[i].clear();
	}
}

void tarjan(int u) {
	vis[u] = 1;
	fa[u] = u;
	for(int i = 0; i < m; i++) {
		if(x[i] == u && vis[y[i]]) {
			z[i] = find(y[i]);
		}
		if(y[i] == u && vis[x[i]]) {
			z[i] = find(x[i]);
		}
	}
	for(int i = 0; i < G[u].size(); i++) {
		int v = G[u][i].ch;
		if(!vis[v]) {
			rdis[v] = rdis[u] + G[u][i].dis;
			tarjan(v);
			fa[v] = u;
		}
	}
}

int main() {
	scanf("%d", &t);
	while(t--) {
		init();
		scanf("%d%d", &n, &m);
		int u, v, dis;
		for(int i = 0; i < n - 1; i++) {
			scanf("%d%d%d", &u, &v, &dis);
			G[u].push_back({v, dis});
			G[v].push_back({u, dis});
		}

		for(int i = 0; i < m; i++) {
			scanf("%d%d", &x[i], &y[i]);
		}

		tarjan(1);

		for(int i = 0; i < m; i++) {
			// printf("%d %d %d\n", x[i], y[i], z[i]);
			printf("%d\n", rdis[x[i]] + rdis[y[i]] - rdis[z[i]] * 2);
		}
	}
	return 0;
}
Echats-wordcloud 文字云图的踩坑点【Unknown series wordCloud】 一直都是报 【ECharts Unknown series wordCloud】这玩意可能要刷脸,祝你好运吧~ 阅读详情

相关推荐

Stata面板数据OLS回归分析实战指南

OLS回归作为计量经济学的核心分析方法,通过最小化残差平方和实现参数估计,广泛应用于经济学实证研究。其技术价值在于模型简洁、结果易于解释,特别适合处理面板数据中的复杂关系。在实际应用中,配合robust标准误能有效解决异方差问题,而固定效应模型则可控制个体特异性。本文以Stata软件为例,详细演示从数据导入、描述性统计到混合OLS和固定效应模型构建的全流程,重点解析面板数据特有的格式设定、模型选择标准以及结果呈现技巧,为经济学研究者提供可直接复用的分析框架。

weixin_29051811的博客 274

hdu2586 How far away?

dfs lca 并查集

weixin_46266058的博客 251

[ESP32S3N16R8][LVGL8.3.0][IDF5.2.3]ST7701S RGB屏幕驱动[vscode最详细配置]

ST7701S ESP32S3 基于ESP-IDF5.2.3编写,编程环境为vscode。本教程详细讲述了esp32s3配置st7701s屏幕驱动以及gt911触摸驱动并关联到lvgl8.3.0,使用IDF5.23示例rgb_panel进行测试删除了其里面的屏幕驱动,改为单独编写屏幕和触摸驱动,最后完成了实列。

qq_44022379的博客 2616

HDU-2586 How far away ?(Tarjian_LCA)

HDU-258 How far away ? 题目 给一颗树,及其每条边权值,求多组两点最短路径, 分析 树上两点最短路径可以先把每个节点到跟节点的权值dis求出,设rt为u,v的LCA。 u,v最短路径 : dis[u]+dis[v]−2∗dis[rt]dis[u] + dis[v] - 2 * dis[rt]dis[u]+dis[v]−2∗dis[rt] 我用的离线Tarjian算法,所以要先...

Stormjing的博客 332

4路QSFP28接口能玩出什么花样?基于璞致VU13P开发板的100G网络测试方案

本文详细介绍了基于璞致PZ-VU13P-KFB开发板构建100G网络测试方案的实战指南。该方案充分利用板载Xilinx Virtex UltraScale+ FPGA的强大算力与4路QSFP28接口,涵盖从光模块选型、Aurora协议配置、开源Corundum方案部署,到误码率测试及散热优化的全链路流程,为高速网络设备研发与验证提供了可靠的硬件平台。

cola5的博客 463

SolidWorks+ADAMS双验证:你的机械臂力矩计算真的靠谱吗?

本文探讨了机械臂力矩计算中手工计算的局限性,并介绍了SolidWorks和ADAMS双验证方法的重要性。通过实际案例展示了动态工况下传统计算方法的误差,详细解析了SolidWorks精准质心捕捉和ADAMS动力学仿真的关键技术,帮助工程师构建计算-仿真-实测闭环验证流程,确保机械臂设计的可靠性和安全性。

grafana6viz的博客 233

hdu2586(带权LCA)

题意: 给定n−1n-1n−1个边的边权,mmm次询问,每次询问任意两点的最短路。 题解: 带权LCA模板。预处理时一并处理两点间最短路即可。 代码: #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 1e5 + 10; con...

solego’s blog 353

无人机VS地面机器人:用AirSim和Gazebo玩转ROS2仿真的5个实战场景对比

本文深度对比了ROS2生态中两大仿真工具AirSim和Gazebo在无人机与地面机器人应用中的表现。通过电力巡检、仓库调度、SLAM建图等5个实战场景,分析了两者在视觉保真度、物理精度、开发效率等方面的差异,并提供了跨平台协作的实用技巧,帮助开发者根据项目需求选择合适的仿真工具。

flink9streamer的博客 902

树上距离HDU2586(在线RMQ算法)

该树的欧拉序列为1 2 4 6 8 6 9 6 4 2 5 7 5 2 1 3 1,搜索时得到6和5首次出现的下标i、j,然后查询该区间深度最小的节点,为6和5号节点的最近公共祖先。欧拉序列就是指在深度遍历过程中依次经过的节点记录下来,把回溯时经过的节点也记录下来,一个节点可能被记录多次,相当于从树根开始,一笔画出一个经过所有节点的回路。1、深度遍历,得到三个数组,每个节点首次出现的下标pos[ ],深度遍历得到的欧拉序列seq[ ],每个节点的深度dep[ ]。2、根据欧拉序列的深度,创建ST。

hwdn3000的博客 291

CNN经典网络模型(二):AlexNet简介及代码实现(PyTorch超详细注释版)

CNN经典网络模型之一:AlexNet,本文包含其简介及代码,在PyTorch中实现,进行超详细注释,适合新生小白阅读学习~

qq_43307074的博客 2万+

Skynet 框架面试题

本文整理了游戏服务端开发面试中 Skynet 框架的高频考点,涵盖底层架构、消息派发、协程调度、网络 I/O、harbor 跨机通信、内存管理、socket 处理、阻塞操作、错误处理等核心内容。全面覆盖 Skynet 框架的原理、使用和实战问题,追求深入准确,拒绝八股文。

小赖的博客 390

【HDU 2586】How far away?(最近公共祖先)

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2586 题意,求一棵树上任意两点的权值和。 分析:在没学最近公共祖先之前一直以为这是道最短路的题,学了最近公共祖先发现利用最近公共祖先去求解十分方便。拿到这个题最先的思路是用Tarjan求LCA的时候,当找到了LCA,用dis数组记录两个询问的点到LCA的距离,但是敲的过程中发现这样不好进行...

a5615024的博客 232

C#客户端对接工厂MES的方法

本文介绍了使用C#实现WebApi客户端与工厂MES系统交互的方法。主要包括四个步骤:1)配置工控机IP地址;2)获取服务器URL;3)创建HttpHelper帮助类实现单例模式HttpClient,提供异步POST请求方法;4)通过实例化帮助类实现设备状态数据的JSON格式发送与接收。该方案采用异步通信方式,支持超时处理,能够满足大多数MES系统交互需求,帮助工程师快速完成设备与MES系统的数据对接。文中给出了核心代码片段和完整的数据交互流程示例。

weixin_39832501的博客 273

HDU 2586 How far away ?(LCA模板 最近公共祖先)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586 Problem Description There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "...

1693

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

HDU2586 How far away ?(LCA求最近公共祖先)

How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 19650    Accepted Submission(s): 7704 Problem Description There are

Mizersy的博客 284

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

HDU - 2586 How far away ?(LCA:最近公共祖先模板)

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this “How far is it if I want to go from house A to house B”? Usually it hard to...

birdmanqin的博客 237

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

hdu 2586 How far away ?(最近公共祖先)

这题和ural 1471除了输入格式不一样外其他的都一样,还有hdu上这题数据太弱了,开始写了一个,hdu上能过,放在ural上去就卡在#wa3了,后来又重写了一个。 #include #include #include #include #include #include #include #include #include using namespace std; const int ma

637

【HDU - 2586】How far away ?(LCA最近公共祖先)

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to...

__似水流年__的博客 296

HDU2586 How far away ?(最近公共祖先lca,离线Tarjan,最短路)

题目: How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 17199    Accepted Submission(s): 6622 Problem Description T

riba2534的博客 647

hdu2586-How far away ?(最近公共祖先(LCA),离线Tarjan算法)

题目来源:http://acm.hdu.edu.cn/php?pid=2586题意从A地到B地,有且只有一条路,那么求路径。 q次询问。思路离线LCA,输入所有的关系,用邻接表进行存储,然后利用Tarjan算法的思想去做这道题,核心公式(假如d指的是从根节点(例如点1)到该点的距离):dis(a,b)=d[a]+d[b]-2*d[lca] 附赠一篇讲解离线查询的博客:http://www.cnb

Crazy 459

hdu 2586 How far away ?(LCA:最近公共祖先)

题目:         链接:点击打开链接 题意:          思路:          代码: #include #include #include using namespace std; const int N = 40040; const int M = 220; struct node{ int from; int to; int n

young TO challenge! 405

hdu 2586 How far away ?(离线求最近公共祖先)

1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 #include<vector> 6 #include<cmath> 7 #include<map> ...

weixin_30386713的博客 68

hdu2586 How far away? LCA

hdu2586 #include #include #include #include using namespace std; #define MAX 40000 struct edge{ int v,w; }; vector mp[MAX]; vector query[MAX]; bool flag[MAX]; int pre[MAX],father[MAX],path[MAX]

Time flies 1944

【LCA最近公共祖先】HDU 2586 How far away ?

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586

F丶轩 708

HDU 2586 How far away ?题解与分析

HDU 2586 How far away ? 【题目大意】:           一个村子里有n个房子,这n个房子用n-1条路连接起来,接下来有m次询问,每次询问两个房子a,b之间的距离是多少。 【分析】:          这是个求最近公共祖先的问题,用临接链表存下每条边和询问的信息,然后跑一遍Tarjan(算法详解见:http://blog.csdn.net/csyzcyj/arti

初学者 1405

hdu2586【How far away ?】

[tarjian离线求lca] hdu2586【How far away ?】 Time Limit: 2000/1000 MS (Java/Others)   Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 13605 Accepted Submission(s): 5101 【Problem Descript

Freddddd 523
上一篇: 蓝书上两道后缀数组题(Uva11107和Uva12206)的后缀自动机解法
下一篇: ACM/ICPC 2018亚洲区预选赛北京网络赛 B.Tomb Raider(暴力)
Cymbals
博客等级 码龄9年 45粉丝 157原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值