zoukankan      html  css  js  c++  java
  • POJ1470 Closest Common Ancestors(LCA入门)

    LCA裸题,读入比较毒瘤

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    const int maxn=1e5;
    int N;
    int head[maxn];
    int tol;
    struct node {
        int u;
        int v;
        int next;
    }edge[maxn]; 
    void addedge (int u,int v) {
        edge[tol].u=u;
        edge[tol].v=v;
        edge[tol].next=head[u];
        head[u]=tol++;
    }
    
    int h[maxn];
    int father[20][maxn];
    int isRoot[maxn];
    void dfs (int x) {
        for (int i=head[x];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            if (v==father[0][x]) continue;
            father[0][v]=x;
            h[v]=h[x]+1;
            dfs(v);
        }
    }
    int lca (int x,int y) {
        if (h[x]<h[y]) swap(x,y);
        for (int i=17;i>=0;i--) 
            if (h[x]-h[y]>>i) x=father[i][x];
        if (x==y) return x;
        for (int i=17;i>=0;i--) {
            if (father[i][x]!=father[i][y]) {
                x=father[i][x];
                y=father[i][y];
            }
        }
        return father[0][x];
    }
    
    int main () {
        while (~scanf("%d",&N)) {
            memset(head,-1,sizeof(head));
            memset(isRoot,0,sizeof(isRoot));
            tol=0;
            memset(h,0,sizeof(h));
            memset(father,0,sizeof(father));
            for (int i=0;i<N;i++) {
                int x,k;
                scanf("%d:(%d)",&x,&k);
                for (int j=0;j<k;j++) {
                    int y;
                    scanf(" %d",&y);
                    addedge(x,y);
                    addedge(y,x);
                    isRoot[y]=1;
                }
            }
            int root;
            for (root=1;root<=N;root++)
                if (!isRoot[root]) break;
            dfs(root);
            for (int i=1;i<=17;i++)
                for (int j=1;j<=N;j++) 
                    father[i][j]=father[i-1][father[i-1][j]];
            int q;
            memset(isRoot,0,sizeof(isRoot));
            scanf("%d",&q);
            for (int i=0;i<q;i++) {
                int x,y;
                scanf(" (%d %d)",&x,&y);
                isRoot[lca(x,y)]++;
            }
            for (int i=1;i<=N;i++) 
                if (isRoot[i]) printf("%d:%d
    ",i,isRoot[i]);
        }
        return 0;
    }
  • 相关阅读:
    java继承中的初始化顺序
    java可访问修饰符
    java简单数据类型转化
    java运算符优先级
    面向切面编程的例子
    什么是面向切面编程
    return 的使用
    通过修改my.ini配置文件来解决MySQL 5.6 内存占用过高的问题
    spring 注入使用注解(不用xml)
    spring在扫描包中的注解类时出现Failed to read candidate component错误
  • 原文地址:https://www.cnblogs.com/zhanglichen/p/12527939.html
Copyright © 2011-2022 走看看