您的位置:首页 > 其它

POJ 1330 解题报告

2014-12-15 03:34 369 查看
这道题似乎是一道很经典的问题,有经典的解法:Tarjan或是RMQ。但是似乎都不是一下能懂。。。

我用的是naive的方法。

1330Accepted524K16MSC++1375B
/*
ID: thestor1
LANG: C++
TASK: poj1330
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

const int MAXN = 100000;

int getheight(int c, int parent[])
{
int h = 0;
while (parent[c] >= 0)
{
c = parent[c];
h++;
}
return h;
}

void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}

int main()
{
int T;
scanf("%d", &T);
int parent[MAXN];
for (int t = 0; t < T; ++t)
{
int N;
scanf("%d", &N);
for (int i = 0; i < N; ++i)
{
parent[i] = -1;
}
for (int i = 0; i < N - 1; ++i)
{
int p, c;
scanf("%d%d", &p, &c);
p--, c--;
parent[c] = p;
}
int c1, c2;
scanf("%d%d", &c1, &c2);
c1--, c2--;
// cout << "c1: " << c1 << ", c2: " << c2 << endl;
int h1, h2;
h1 = getheight(c1, parent), h2 = getheight(c2, parent);
// cout << "h1: " << h1 << ", h2: " << h2 << endl;
if (h1 < h2)
{
swap(h1, h2);
swap(c1, c2);
}
while (h1 > h2)
{
c1 = parent[c1];
h1--;
}
while (c1 != c2)
{
c1 = parent[c1];
c2 = parent[c2];
}
printf("%d\n", c1 + 1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: