【HDU6031】Innumerable Ancestors(二分+LCA)

记录一个菜逼的成长。。

题目链接

题目大意:
给你n个点树,m个查询
每次查询给出两个点集A,B。
xA,yB 使得 lca(x,y)

倍增lca相关知识
用倍增法处理出lca
然后对每个查询二分深度
处理出A集合的点在二分深度的祖先集合
然后判断B集合里是否存在一个点的祖先在上述集合里

#include 
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
const int maxn = 100000 + 10;
struct Edge{
    int to,next;
}edge[maxn*2];
int head[maxn],cnt;
int deep[maxn],anc[maxn][20];
int n,m;
void add(int u,int v)
{
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
void init()
{
    cl(head,-1);
    cl(deep,0);
    cl(anc,-1);
    cnt = 0;
}
//倍增lca
void dfs(int u,int pre,int d)
{
    deep[u] = d;
    for( int i = head[u]; ~i; i = edge[i].next ){
        int v = edge[i].to;
        if(v == pre)continue;
        anc[v][0] = u;
        dfs(v,u,d+1);
    }
}
void Init()
{
    for( int j = 1; (1<for( int i = 1; i <= n; i++ ){
            if(anc[i][j-1] != -1){
                anc[i][j] = anc[anc[i][j-1]][j-1];
            }
        }
    }
}
int lca(int a,int b)
{
    int i,j;
    if(deep[a] < deep[b])swap(a,b);
    for( i = 0; (1<for( j = i; j >= 0; j-- ){
        if(deep[a] - (1<= deep[b]){
            a = anc[a][j];
        }
    }
    if(a == b)return a;

    for( j = i; j >= 0; j-- ){
        if(anc[a][j] != -1 && anc[a][j] != anc[b][j]){
            a = anc[a][j];
            b = anc[b][j];
        }
    }
    return anc[a][0];
}
/***********************/
int query(int u,int d)
{
    if(d < 0)return -1;
    if(d == 0)return u;
    int i;
    for( i = 0; (1<for( ; i >= 0; i-- ){
        if(d - (1<= 0){
            d -= (1<return u;
}
int a[maxn],b[maxn];
int k1,k2;
bool check(int x)
{
    set<int>s;
    for( int i = 0; i < k1; i++ ){
        int dis = deep[a[i]] - x;
        int ret = query(a[i],dis);
        if(ret == -1)continue;
        s.insert(ret);
    }
    for( int i = 0; i < k2; i++ ){
        int dis = deep[b[i]] - x;
        int ret = query(b[i],dis);
        if(s.count(ret))return true;
    }
    return false;
} 
int main()
{
    while(~scanf("%d%d",&n,&m)){
        init();
        for( int i = 0; i < n-1; i++ ){
            int u,v;
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        dfs(1,1,1);
        Init();

        while(m--){
            scanf("%d",&k1);
            int l = 1,r = 1;
            for( int i = 0; i < k1; i++ )
                scanf("%d",a+i),r = max(r,deep[a[i]]);
            scanf("%d",&k2);
            for( int i = 0; i < k2; i++ )
                scanf("%d",b+i);
            int ans;
            while(l <= r){
                int mid = (l + r) >> 1;
                if(check(mid)){
                    ans = mid;
                    l = mid + 1;
                }
                else {
                    r = mid - 1;
                }
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}

你可能感兴趣的:(图论,LCA,图论,其他,hdu)