博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ-1986 Distance Queries
阅读量:6867 次
发布时间:2019-06-26

本文共 2145 字,大约阅读时间需要 7 分钟。

Distance Queries
Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 13987 Accepted: 4924
Case Time Limit: 1000MS

Description

Farmer John's cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in "Navigation Nightmare",followed by a line containing a single integer K, followed by K "distance queries". Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ's distance queries as quickly as possible!

Input

* Lines 1..1+M: Same format as "Navigation Nightmare"
* Line 2+M: A single integer, K. 1 <= K <= 10,000
* Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.

Output

* Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.

Sample Input

7 61 6 13 E6 3 9 E3 5 7 S4 1 3 N2 4 20 W4 7 2 S31 61 42 6

Sample Output

13336

Hint

Farms 2 and 6 are 20+3+13=36 apart. 
这题目别想多,跟方向没关系,LCA。
关键在于怎么将距离整出来,我们可以有这么一个方程,
ans[id]=pre[v].len+pre[u].len-2*pre[Find(v)].len; 用一个图来表示就是这样: pre[v].len就是1到3的距离, pre[u].len就是1到4的距离。 pre[Find(v)].len就是1到2的距离。 这样就很好解决了所有的问题了。 还有就是,重要的事情说三遍:并查集要压缩路径!并查集要压缩路径!并查集要压缩路径! 之前几次忘了压缩,直接TLE;一脸懵逼 附上AC代码:
1 #include
2 #include
3 #include
4 #include
5 #include
6 using namespace std; 7 struct Node{ 8 int f; 9 int len;10 }pre[50080];11 vector
>query[50050];12 vector
>vec[50100];13 int ans[50050],vis[50100];14 int Find(int x)15 {16 if(pre[x].f==x)17 {18 return x;19 }20 else21 {22 pre[x].f=Find(pre[x].f);23 return pre[x].f;24 }25 }26 int dfs(int u,int fa,int length)27 {28 pre[u].f=u;29 pre[u].len=pre[fa].len+length;30 vis[u]=1;31 for(int i=0;i
>k;65 for(int i=0;i

 

 

转载于:https://www.cnblogs.com/ISGuXing/p/7220719.html

你可能感兴趣的文章
我的友情链接
查看>>
每天进步一点点:(21)SAMBA笔记
查看>>
ajax结构体请求后台
查看>>
linux mint 关于web开发的环境配置
查看>>
10g直接删除数据文件后的启动
查看>>
JavaScript ~~~~~ 清空上一次上传的文件
查看>>
我的友情链接
查看>>
STDIN_FILENO和stdin的区别
查看>>
条形图对比方式一
查看>>
Google Guava提供了Joiner类的初探
查看>>
搭建高可用mongodb集群(三)—— 深入副本集内部机制
查看>>
快递查询文档
查看>>
VIM常用替换,查找命令
查看>>
2010年3月计算机等级考试二级C笔试试题(文字版)
查看>>
Nginx+Tomcat动静分离架构
查看>>
我的友情链接
查看>>
Strategy Design Pattern(策略模式)
查看>>
龙年第一篇
查看>>
Linux 结构化命令(while/if/for)
查看>>
在Linux系统上获取命令的帮助信息,man文档的章节的划分
查看>>