当前位置:网站首页>Recent public ancestor offline practice (tarjan)
Recent public ancestor offline practice (tarjan)
2022-07-01 22:30:00 【Zqchang】
List of articles
Online and offline
Online and offline are generally for questions that are asked
Online practice : Every time I read a question , You can calculate an answer immediately , Then the output
Offline approach : We must first read all the questions in a unified way , Then after unified calculation , Then output all queries in a unified way
tarjan O(n + m)
n It's the number of nodes ,m Is the number of inquiries
The essence is to optimize the upward marking method
Upward marking method
See an online practice for details
In the depth first traversal process, all points are divided into three categories
1. It's been traversed , And back to the point , Searched , And the subtree was searched
2. Branch being searched
3. Points that have not been searched 
Suppose you search from left to right , It forms such a tree. Green is the first , Red is the second , That is, a path , The others are the third

For the point being searched , Let's look for related questions , You can see from the picture above , Current inquiry point x And the common ancestor of the green part are the general points of the path , Because the subtree at the midpoint of the path can be merged into that point , Finally, when we seek common ancestors , Just look at the point to which that point is merged , It can be realized by combining and searching sets , This is to find the ancestor node
such , Each point will be traversed only once , It will only be merged once , For each query, it will only be queried once
The main idea
When we traverse the current branch , For the common ancestor of all nodes related to this point , We can find out , If this point has been traversed , The common ancestor of the whole subtree is the point in the path , That is, the root node of the subtree , That is, after traversing a point every time , You can merge the current point directly into the root node , When we look up , You can directly check who is the representative element of the current element in the parallel search set , This representative element is its common ancestor
Pay attention to when to merge , That is, after the backtracking , Then merge it into the parent node
Example
distance
The meaning of the question is to ask for the distance between two points 
The method is shown in the figure , Calculate the distance to the root node , Subtract twice the distance of the common ancestor
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
#define PII pair<int, int>
const int N = 1e4 + 10;
#define x first
#define y second
vector<PII> v[N];
int n, m, a, b, k;
int dist[N];// Store the distance from each point to the root node
int p[N];
int res[N * 2];// Save the answer
int st[N];
vector<PII> query[N]; // first Another query save point ,second Save query number
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void dfs(int u, int fa)
{
for(auto i : v[u])
{
if(i.x == fa) continue;
dist[i.x] = dist[u] + i.y;
dfs(i.x, u);
}
}
void tarjan(int u)
{
st[u] = 1;
for(auto i : v[u])
{
if(!st[i.x])
{
tarjan(i.x);
p[i.x] = u;
}
}
for(auto i : query[u])
{
if(st[i.x] == 2)// Check whether another point has been traced , If you haven't looked back, jump
{
int anc = find(i.x);
res[i.y] = dist[u] + dist[i.x] - dist[anc] * 2;
}
}
st[u] = 2;
}
signed main()
{
cin >> n >> m;
for(int i=1; i<=n-1; i++)
{
cin >> a >> b >> k;
v[a].push_back({
b, k});
v[b].push_back({
a, k});
}
for(int i=1; i<=m; i++)
{
cin >> a >> b;
if(a != b)
{
query[a].push_back({
b, i});
query[b].push_back({
a, i});
}
}
for(int i=1; i<=n; i++) p[i] = i;
dfs(1, -1);
tarjan(1);
for(int i=1; i<=m; i++) cout << res[i] << endl;
return 0;
}
边栏推荐
- require与import的区别和使用
- Interview question: what is the difference between MySQL's Union all and union, and how many join methods MySQL has (Alibaba interview question) [easy to understand]
- Case of camera opening by tour
- 多种智能指针
- Significance and measures of security encryption of industrial control equipment
- 焱融看 | 混合云时代下,如何制定多云策略
- Test cancellation 1
- 信标委云原生专题组组长,任重道远!
- 【juc学习之路第9天】屏障衍生工具
- MySQL清空表数据
猜你喜欢

AirServer2022最新版功能介绍及下载

企业架构与项目管理的关联和区别

Copy ‘XXXX‘ to effectively final temp variable

Go - exe corresponding to related dependency

Introduction à l'ingénierie logicielle (sixième édition) notes d'examen de Zhang haifan
![[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial](/img/ac/655fd534ef7ab9d991d8fe1c884853.png)
[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial

“丝路正青春 风采看福建”在闽外籍青年短视频大赛火热征集作品中

News classification based on LSTM model

ICML2022 | 基于元语义正则化的介入性对比学习

K-means based user portrait clustering model
随机推荐
Electron学习(三)之简单交互操作
Flume interview questions
信标委云原生专题组组长,任重道远!
地图其他篇总目录
MySQL series transaction log redo log learning notes
【生态伙伴】鲲鹏系统工程师培训
工控设备安全加密的意义和措施
What is the difference between consonants and Initials? (difference between initials and consonants)
从MLPerf谈起:如何引领AI加速器的下一波浪潮
News classification based on LSTM model
【MySQL】数据库优化方法
手动实现function isInstanceOf(child,Parent)
上半年暂停考试要补考?包含监理工程师、建筑师等十项考试
Show member variables and methods in classes in idea
100年仅6款产品获批,疫苗竞争背后的“佐剂”江湖
Why does blocprovider feel similar to provider?
【直播回顾】战码先锋首期8节直播完美落幕,下期敬请期待!
vscode的使用
Talking from mlperf: how to lead the next wave of AI accelerator
"The silk road is in its youth and looks at Fujian" is in the hot collection of works in the Fujian foreign youth short video competition