关闭

poj 1330 Nearest Common Ancestors lca rmq在线算法

标签: poj 1330Nearest Common Anceslcarmq在线算法
226人阅读 评论(0) 收藏 举报
分类:

题意:裸的lca


思路:直接上rmq在线模板


题目链接:http://poj.org/problem?id=1330


#include <cstdio>
#include <cstring>
#include <algorithm>

#pragma warning (disable: 4996)

using namespace std;

const int maxn = 10005;

struct edge
{
	int u, v, next;
}e[maxn];
int head[maxn], cnt;
int n;
int vs[maxn << 1];
int dep[maxn << 1];
int id[maxn];
int dp[maxn << 1][20];
bool in[maxn];
int root;

void init()
{
	cnt = 0;
	memset(in, false, sizeof(in));
	memset(head, -1, sizeof(head));
}

int Min(int x, int y)
{
	return dep[x] <= dep[y] ? x : y;
}

void addedge(int u, int v)
{
	e[cnt].u = u, e[cnt].v = v, e[cnt].next = head[u], head[u] = cnt++;
}

void rmq_init(int n)
{
	for (int i = 1; i <= n; i++)
		dp[i][0] = i;
	for (int j = 1; (1 << j) <= n; j++)
	{
		for (int i = 1; i + (1 << j) - 1 < n; i++)
			dp[i][j] = Min(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
	}
}

int rmq(int l, int r)
{
	int k = 0;
	while ((1 << (k + 1)) <= (r - l + 1)) k++;
	return Min(dp[l][k], dp[r - (1 << k) + 1][k]);
}

void dfs(int u, int p, int d, int &k)
{
	id[u] = k;
	vs[k] = u;
	dep[k++] = d;
	int v;
	for (int i = head[u]; i != -1; i = e[i].next)
	{
		v = e[i].v;
		if (v != p)
		{
			dfs(v, u, d + 1, k);
			vs[k] = u;
			dep[k++] = d;
		}
	}
}


void build()
{
	scanf("%d", &n);
	for (int i = 0; i < n - 1; i++)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		addedge(u, v);
		in[v] = true;
	}
	for (int i = 1; i <= n; i++)
	{
		if (!in[i])
		{
			root = i;
			break;
		}
	}
}

int lca(int u, int v)
{
	return vs[rmq(min(id[u], id[v]), max(id[u], id[v]))];
}

void solve()
{
	int u, v, k = 0;
	scanf("%d%d", &u, &v);
	dfs(root, -1, 0, k);
	rmq_init(n * 2);
	int ans = lca(u, v);
	printf("%d\n", ans);
}

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		init();
		build();
		solve();
	}
	return 0;
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:49284次
    • 积分:1569
    • 等级:
    • 排名:千里之外
    • 原创:109篇
    • 转载:3篇
    • 译文:0篇
    • 评论:16条
    最新评论