zoukankan      html  css  js  c++  java
  • 【JZOJ3054】祖孙询问【LCA】

    题目大意:

    题目链接:https://jzoj.net/senior/#main/show/3054
    给出一棵有根树,询问xxyy的祖孙关系。


    思路:

    水题。
    直接求一遍lcalca,然后如果lcalcaxxyy中的一个,那么xxyy就是有祖孙关系的,否则就没有祖孙关系。


    代码:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    const int N=40010;
    const int LG=20;
    int n,m,x,y,tot,root,head[N],f[N][LG+1],dep[N];
    
    struct edge
    {
    	int next,to;
    }e[N*2];
    
    void add(int from,int to)
    {
    	e[++tot].to=to;
    	e[tot].next=head[from];
    	head[from]=tot;
    }
    
    void dfs(int x,int fa)
    {
    	dep[x]=dep[fa]+1;
    	f[x][0]=fa;
    	for (int i=1;i<=LG;i++)
    		f[x][i]=f[f[x][i-1]][i-1];
    	for (int i=head[x];~i;i=e[i].next)
    	{
    		int v=e[i].to;
    		if (v!=fa) dfs(v,x);
    	}
    }
    
    int lca(int x,int y)
    {
    	if (dep[x]<dep[y]) swap(x,y);
    	for (int i=LG;i>=0;i--)
    		if (dep[f[x][i]]>=dep[y]) x=f[x][i];
    	if (x==y) return x;
    	for (int i=LG;i>=0;i--)
    		if (f[x][i]!=f[y][i])
    		{
    			x=f[x][i];
    			y=f[y][i];
    		}
    	return f[x][0];
    }
    
    int main()
    {
    	memset(head,-1,sizeof(head));
    	scanf("%d",&n);
    	for (int i=1;i<=n;i++)
    	{
    		scanf("%d%d",&x,&y);
    		if (y==-1) root=x;
    		else
    		{
    			add(x,y);
    			add(y,x);
    		}
    	}
    	dfs(root,0);
    	scanf("%d",&m);
    	while (m--)
    	{
    		scanf("%d%d",&x,&y);
    		int LCA=lca(x,y);
    		if (LCA==x) printf("1
    ");
    		else if (LCA==y) printf("2
    ");
    		else printf("0
    ");
    	}
    	return 0;
    }
    
  • 相关阅读:
    PSP第二次总结
    周总结02
    四则运算2
    构建执法阅读笔记01
    周学习进度01
    暑假生活一
    构建之法阅读笔记03
    构建之法阅读笔记02
    个人课程总结
    软工大二下半年第十六周学习进度
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998295.html
Copyright © 2011-2022 走看看