Hihocoder 1067
2024-09-08 19:26:12
最近公共祖先二 离线算法
/**/
#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:
*/
最新文章
- Android 弱引用和软引用
- JS倒计时执行操作
- web 开发入门
- div内填内容
- this.name=name;和this.setName(name);的区别
- EChars学习-1
- Matlab的libsvm的安装
- boot/head.S
- 3.发布Maven项目到nexus中
- 复杂的databinding接受Ilist作为数据源
- poj 2349 Arctic Network
- line-height系列——定义和工作原理总结
- elasticsearch系列(二) esrally压测
- Linux---设备文件名和挂载点
- 大菲波数(Fibonacci)java大数(hdu1715)
- Linux的任务计划管理
- Java入门:基础算法之产生随机数
- Caffe学习笔记(二):Caffe前传与反传、损失函数、调优
- 【转载】分布式之redis复习精讲
- vue-cli脚手架build目录下utils.js工具配置文件详解