2015北京网络赛 Couple Trees

题意:两棵树,求不同树上两个节点的最近公共祖先

思路:比赛时看过的队伍不是很多,没有仔细想。今天补题才发现有个 倍增算法,自己竟然不知道。

    解法来自 qscqesze ,这个其实之前如果了解过倍增的话还是不是很难,不过这题的数据也不是很给力,极限数据理论上是过不了的。

    其他解法有树链剖分?并不是很清楚。就这样水过了吧。。。

 #include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#define LL long long
#define eps 1e-8
#define INF 0x3f3f3f3f
#define MAXN 100005
using namespace std; int f1[MAXN][], f2[MAXN][];
int deep1[MAXN], deep2[MAXN];
int step1, step2, ans;
void work(int x, int y){
step1 = step2 = ;
while (x != y){
if (x < y){
//x < y means y is not x's ancestor, so let y up
for (int i = ; i >= ; i--){
if (f2[y][i] > x){
y = f2[y][i];
step2 += << i;
break;
}
}
y = f2[y][];
step2++;
}
else{
for (int i = ; i >= ; i--){
if (f1[x][i] > y){
x = f1[x][i];
step1 += << i;
break;
}
}
x = f1[x][];
step1++;
}
}
ans = x;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif // OPEN_FILE
int n, m;
while (~scanf("%d%d", &n, &m)){
int x, y;
deep1[] = deep2[] = ;
for (int i = ; i <= ; i++){
f1[][i] = f2[][i] = ;
}
for (int i = ; i <= n; i++){
scanf("%d", &x);
f1[i][] = x;
deep1[i] = deep1[x] + ;
for (int j = ; j <= ; j++){
f1[i][j] = f1[f1[i][j - ]][j - ];
}
}
for (int i = ; i <= n; i++){
scanf("%d", &x);
f2[i][] = x;
deep2[i] = deep2[x] + ;
for (int j = ; j <= ; j++){
f2[i][j] = f2[f2[i][j - ]][j - ];
}
}
ans = ;
for (int i = ; i <= m; i++){
scanf("%d%d", &x, &y);
x = (x + ans) % n + ;
y = (y + ans) % n + ;
work(x, y);
printf("%d %d %d\n", ans, step1, step2);
}
}
}    

最新文章

  1. NBUT 1457 莫队算法 离散化
  2. HTML5 图片缩放功能
  3. app开发方式大汇总
  4. jbpm的学习 出处http://blog.csdn.net/hxirui/article/details/1221911
  5. DataTable .Load 方法 (IDataReader)
  6. 10个jQuery插件分享
  7. 《Linux下sed命令的使用》
  8. UIPickerView用法(左右比例,整体大小,字体大小)
  9. Android SDK Manager无法更新问题解决
  10. Solr6.6 创建core
  11. 2020考研-必须了解的干货&quot;极限微分和你说的悄悄话&quot;
  12. logrotate异常排查
  13. C# -- 随机数产生的字母金字塔
  14. websocket Tomcat JSP Demo
  15. Netty4.0源码解析 NioServerSocketChannel
  16. 【JMeter】【接口测试】csv参数化,数据驱动,自动化测试
  17. 20170724 Airflow官网资料学习
  18. Codeforces 101572 D - Distinctive Character
  19. 分布式理论(七)—— 一致性协议之 ZAB
  20. 50.EasyGank妹纸App

热门文章

  1. vue中使用viewerjs
  2. poj1284 && caioj 1159 欧拉函数1:原根
  3. vue2.0移动端自定义性别选择提示框
  4. 【转】C# 正则表达式大全
  5. Trustie站点代码托管使用指南
  6. Hello World FastCGI
  7. cocos2d-iphone 动作
  8. jsp输出当前时间
  9. PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(1)
  10. dedecms4张关键表解析之2