poj 1470 LCA倍增 裸

Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u,v) the program determines the closest common ancestor of u and v in the tree. The closest common ancestor of two nodes u and v is the node w that is an ancestor of both u and v and has the greatest depth in the tree. A node can be its own ancestor (for example in Figure 1 the ancestors of node 2 are 2 and 5)
Input
The data set, which is read from a the std input, starts with the tree description, in the form:

nr_of_vertices
vertex:(nr_of_successors) successor1 successor2 … successorn

where vertices are represented as integers from 1 to n ( n <= 900 ). The tree description is followed by a list of pairs of vertices, in the form:
nr_of_pairs
(u v) (x y) …

The input file contents several data sets (at least one).
Note that white-spaces (tabs, spaces and line breaks) can be used freely in the input.
Output
For each common ancestor the program prints the ancestor and the number of pair for which it is an ancestor. The results are printed on the standard output on separate lines, in to the ascending order of the vertices, in the format: ancestor:times
For example, for the following tree:

Sample Input
5
5:(3) 1 4 2
1:(0)
4:(0)
2:(1) 3
3:(0)
6
(1 5) (1 4) (4 2)
(2 3)
(1 3) (4 3)
Sample Output
2:1
5:5
Hint
Huge input, scanf is recommended.

大意是说,给出一棵树(包含 N 个点),然后给出 M 次询问,每次询问都是两个点的编号,他们一定有一个最近公共祖先,最后让你输出每个点被当做最近公共祖先的次数(是 0 次的话就不输出了)。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
using namespace std;

#define N 1010
int n;
vector<int> v[N<<2];
int vis[N];
int deep[N];
int g[N][21];
map<int,int> mp;

void dfs(int x,int de)
{
    for(int i=0;i<v[x].size();i++)
    {
        if(!deep[v[x][i]])
        {
            deep[v[x][i]]=deep[x]+1;
            g[v[x][i]][0]=x;
            dfs(v[x][i],de+1);
        }
    }
}

int lca(int a,int b)
{
    if(deep[a]<deep[b]) swap(a,b);
    int t=deep[a]-deep[b];
    for(int i=0;i<=20;i++)
    {
        if((1<<i)&t)
            a=g[a][i];
    }
    if(a==b) return a;
    for(int i=20;i>=0;i--)
    {
        if(g[a][i]!=g[b][i])
        {
            a=g[a][i];
            b=g[b][i];
        }
    }
    return g[a][0];
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
    mp.clear();
    memset(g,0,sizeof(g));
    for(int i=1;i<=n;i++)
        v[i].clear();
    memset(deep,0,sizeof(deep));
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)
    {
        int d,k;
        scanf("%d:(%d)",&d,&k);
        for(int j=1;j<=k;j++)
        {
            int c;
            scanf("%d",&c);
            v[d].push_back(c);
            vis[c]++;
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(!vis[i])
        {
            dfs(i,1);
            break;
        }
    }
    for(int j=1;j<=20;j++)
    {
        for(int i=1;i<=n;i++)
        {
            g[i][j]=g[g[i][j-1]][j-1];
        }
    }
    int m;
    scanf("%d",&m);
    for(int i=1;i<=m;i++){
        int a,b;
        scanf(" (%d %d)",&a,&b);
        mp[lca(a,b)]++;
    }
    for(map<int,int>::iterator iter=mp.begin();iter!=mp.end();iter++){
        printf("%d:%d\n",iter->first,iter->second );
    }
    }
}
### POJ 1330 题解 POJ 1330 是一道经典的最近公共祖先 (Least Common Ancestor, LCA) 问题。该题的核心在于如何高效地求解两节点之间的最近公共祖先。 #### 倍增算法简介 倍增方法是一种高效的在线求解 LCA 的方式,其时间复杂度为 \(O((n+q)\log n)\),其中 \(n\) 表示树中的节点数量,\(q\) 表示查询次数。此方法通过预处理的方式记录每个节点向上跳跃若干步后的父节点位置,从而加速查询过程。 具体来说,定义数组 `fa[i][j]` 表示从节点 \(i\) 向上跳 \(2^j\) 步所到达的节点编号。为了支持这一操作,我们需要满足如下递推关系: \[ \text{fa}[i][j] = \begin{cases} \text{parent}(i), & j = 0 \\ \text{fa}[\text{fa}[i][j-1]][j-1], & j > 0 \end{cases} \] 这种预处理可以通过深度优先搜索 (DFS) 完成,在 DFS 过程中同时计算每个节点的深度以及它们的倍增父节点表。 #### 查询阶段 在实际查询过程中,假设我们要查找节点 \(a\) 和 \(b\) 的最近公共祖先,则分为以下几个部分: 1. **调整深度一致** 如果当前两个节点的深度不相同,则将较深的节点不断向上提升至两者深度相等的位置。这一步利用了倍增数组 `fa[i][j]` 来快速跳跃多个层次。 2. **同步爬升** 当两个节点处于同一深度时,让它们逐步向上移动直至相遇于某个共同祖先处。为了避免逐层遍历带来的效率低下问题,同样采用倍增策略按指数级跳跃。 最终返回的结果即为最后一次未分叉前的状态作为答案。 以下是基于以上逻辑的一个简单实现代码片段: ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 5e4 + 5; vector<int> adj[MAXN]; int depth_[MAXN]; // 存储每个结点的深度 int fa[MAXN][20]; // 记录每个结点向上跳2^k步的父亲 void dfs(int u, int parent){ depth_[u]=depth_[parent]+1; fa[u][0]=parent; for(auto v : adj[u]){ if(v != parent){ dfs(v,u); } } } // 初始化fa[][]表格 void preprocess(int N){ memset(fa,-1,sizeof(fa)); for(int k=1;k<20;k++){ for(int i=1;i<=N;i++){ if(fa[i][k-1]!=-1){ fa[i][k]=fa[fa[i][k-1]][k-1]; } } } } int get_lca(int a,int b){ if(depth_[a]<depth_[b]) swap(a,b); // 将a提到和b相同的高度 for(int k=19;k>=0;k--){ if(fa[a][k]!=-1 && depth_[fa[a][k]] >= depth_[b]){ a=fa[a][k]; } } if(a==b)return a; // 同步爬升 for(int k=19;k>=0;k--){ if(fa[a][k]!=-1 && fa[b][k]!=-1 && fa[a][k]!=fa[b][k]){ a=fa[a][k]; b=fa[b][k]; } } return fa[a][0]; } ``` 上述程序实现了完整的倍增法用于解决LCA问题的功能模块化设计[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值