POJ 1470 LCA 公共祖先

裸题一个


/*
ID: CUGB-wwj
PROG:
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define INF 1111111111
#define MAXN 1005
#define MAXM 1000005
#define L(x) x<<1
#define R(x) x<<1|1
#define eps 1e-4
using namespace std;
vector<int>tree[MAXN], ask[MAXN];
int father[MAXN], vis[MAXN], ans[MAXN], in[MAXN];
int n, m, c;
void init()
{
    for(int i = 0; i <= n; i++)
    {
        father[i] = i;
        vis[i] = 0;
        tree[i].clear();
        ask[i].clear();
        ans[i] = 0;
        in[i] = 0;
    }
}
int find(int x)
{
    if(father[x] == x) return x;
    int t = find(father[x]);
    father[x] = t;
    return t;
}
void LCA(int u)
{
    father[u] = u;
    int size = tree[u].size();
    for(int i = 0; i < size; i++)
    {
        LCA(tree[u][i]);
        father[tree[u][i]] = u;
    }
    vis[u] = 1;
    size = ask[u].size();
    for(int i = 0; i < size; i++)
        if(vis[ask[u][i]] == 1)
            ans[find(ask[u][i])]++;
}
int main()
{
    int x, y, t;
    while(scanf("%d", &n) != EOF)
    {
        init();
        for(int i = 1; i <= n; i++)
        {
            scanf("%d:(%d)", &x, &t);
            while(t--)
            {
                scanf("%d", &y);
                tree[x].push_back(y);
                in[y]++;
            }
        }
        scanf("%d", &m);
        for(int i = 1; i <= m; i++)
        {
            scanf(" (%d %d)", &x, &y);
            ask[x].push_back(y);
            ask[y].push_back(x);
        }
        for(int i = 1; i <= n; i++)
            if(in[i] == 0) LCA(i);
        for(int i = 1; i <= n; i++)
            if(ans[i]) printf("%d:%d\n", i, ans[i]);
    }
    return 0;
}


你可能感兴趣的:(C++,tree)