ZOJ-1141

来源:互联网 发布:视频变速播放软件 编辑:程序博客网 时间:2024/05/12 22:48

求树中两点最近公共祖先,本题我是用的最直接的求两点路径,然后从根开始遍历求公共点,这种算法是最搓的。。在ZOJ上可以过,POJ上就TLE。。有空看看LCA相关算法

#include<cstdio>#include<cstdlib>#include<cstring>#include<iostream>#include<deque>#include<map>using namespace std;int main(){    int n, m;    deque<int> P, Q;    map<int, int> M;    while (scanf("%d", &n) != EOF)    {        int *p = (int *) malloc((n + 1) * sizeof(int));        for (int i = 1; i <= n; i++)            p[i] = 0;        for (int i = 0; i < n; i++)        {            int v, c, t;            scanf("%d:(%d)", &v, &c);            while (c--)            {                scanf("%d", &t);                p[t] = v;            }        }        scanf("%d", &m);        int a, b;        M.clear();        while (m--)        {            cin >> ws;            scanf("(%d,%d)", &a, &b);            P.clear();            Q.clear();            while (a)            {                P.push_front(a);                a = p[a];            }            while (b)            {                Q.push_front(b);                b = p[b];            }            int res;            while (!P.empty() && !Q.empty() && P.front() == Q.front())            {                res = P.front();                P.pop_front();                Q.pop_front();            }            if (M.find(res) != M.end())                M[res]++;            else                M[res] = 1;        }        for (map<int, int>::iterator it = M.begin(); it != M.end(); it++)            printf("%d:%d\n", (*it).first, (*it).second);        free(p);    }    return 0;}


0 0
原创粉丝点击