最近公共祖先二 离线算法

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue> typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
typedef pair<int, int> P;
#define x first
#define y second
#define pb push_back
bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
const double PI = acos(-1.0), ESP = 1e-10;
const LL INF = 99999999999999;
const int inf = 999999999, N = 1e5 + 24;
vector<int> G[N];
vector<P> Q[N];
map<string, int> H;
string a, b, m[N];
int A, B, fa[N], n, k, c, ans[N];
int fnd(int x) { return x == fa[x] ? x : fa[x] = fnd(fa[x]); }
void dfs(int u, int p)
{
fa[u] = u;
for(auto v : G[u]) if(v != p) dfs(v, u);
for(auto v : Q[u]) if(fa[v.x]) ans[v.y] = fnd(v.x);
fa[u] = p;
} int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
scanf("%d", &n);
while(n--) {
cin >> a >> b;
if(!(A = H[a])) { A = H[a] = ++c; m[c] = a;}
if(!(B = H[b])) { B = H[b] = ++c; m[c] = b;}
G[A].pb(B); G[B].pb(A);
}
scanf("%d", &k);
for(int i = 1; i <= k; i++) {
cin >> a >> b;
A = H[a]; B = H[b];
Q[A].pb(P(B, i)); Q[B].pb(P(A, i));
}
dfs(1, 0);
for(int i = 1; i <= k; i++) cout << m[ans[i]] << "\n"; return 0;
}
/*
input:
output:
modeling:
methods:
complexity:
summary:
*/

最新文章

  1. Android 弱引用和软引用
  2. JS倒计时执行操作
  3. web 开发入门
  4. div内填内容
  5. this.name=name;和this.setName(name);的区别
  6. EChars学习-1
  7. Matlab的libsvm的安装
  8. boot/head.S
  9. 3.发布Maven项目到nexus中
  10. 复杂的databinding接受Ilist作为数据源
  11. poj 2349 Arctic Network
  12. line-height系列——定义和工作原理总结
  13. elasticsearch系列(二) esrally压测
  14. Linux---设备文件名和挂载点
  15. 大菲波数(Fibonacci)java大数(hdu1715)
  16. Linux的任务计划管理
  17. Java入门:基础算法之产生随机数
  18. Caffe学习笔记(二):Caffe前传与反传、损失函数、调优
  19. 【转载】分布式之redis复习精讲
  20. vue-cli脚手架build目录下utils.js工具配置文件详解

热门文章

  1. centos7.9重启后,主机名会变为IP地址
  2. go语言web框架-如何使用gin教程+react实现web项目
  3. js 秒转时分秒
  4. PgBouncer连接池工具
  5. Flask的介绍、安装和使用
  6. ADC参悟
  7. Linux日常指令
  8. iframe 嵌套别的系统不显示,父窗口不响应
  9. springboot项目打成jar包,启动指定外部的yml文件
  10. CSS设置边距