Nearest Common Ancestors Poj1330

来源:互联网 发布:spss软件应用例子 编辑:程序博客网 时间:2024/04/30 10:44
//本题用i代表每个结点,数组f[i],d[i],s[i]分别映射到该节点的父节点信息,深度信息,儿子信息。
<span style="font-family: Arial, Helvetica, sans-serif;">#include<iostream></span>
#include<vector>#include<cstdio>#include<cstdlib>using namespace std;const int N = 10000 + 5;vector<int> s[N];int f[N];int d[N];void DFS(int i, int dep)            //计算每个结点的深度{    d[i] = dep;    for (vector<int>::iterator it = s[i].begin(); it != s[i].end(); ++it)        DFS(*it, dep + 1);}int main(){    int t, n;    scanf("%d", &t);    while (t--) //循环t次    {        scanf("%d", &n);        //memset(f, -1, sizeof(f));        for (int &tem : f)            tem = -1;        for (int i = 0; i < n - 1; ++i) //输入n - 1条边关系        {            int x, y;            scanf("%d%d", &x, &y);            f[y - 1] = x - 1;   //处理y的父节点属性            s[x - 1].push_back(y - 1);   //处理x的儿子结点属性        }        //处理结点的层次属性        int r;  //保存根节点        for (r = 0; f[r] >= 0; r++) //寻找根节点        DFS(r, 0);      //处理结点的层次        int x, y;        scanf("%d%d", &x, &y);      //输入目标结点        x--;        y--;        while (y != x)        {            if (d[x] > d[y])                x = f[x];            else                y = f[y];        }        printf("%d\n", x + 1);    }    return 0;}

0 0
原创粉丝点击