zoukankan      html  css  js  c++  java
  • 【51nod】猴猴的比赛【dfs】

    题目大意:

    题目链接:https://www.51nod.com/Contest/Problem.html#contestProblemId=1150
    猴猴今天要和小伙伴猩猩比赛爬树,为了公平不碰撞,猴猴和猩猩需要在不同的树上攀爬。于是它们选了两颗节点数同为n的树,并将两棵树的节点分别以1~n标号(根节点标号为1),但两棵树的节点连接方式不尽相同。

    现在它们决定选择两个标号的点进行比赛。为了方便统计,规定它们比赛中必须都向上爬。(即选定的赛段节点u→节点v都必须指向叶子方向)请你求出这两棵树上共有多少对节点满足比赛的需求。


    思路:

    我们对第一棵树的每一个节点按dfsdfs序标号。然后顺便求出每一个节点为根的子树的编号区间[Lx,Rx][L_x,R_x]
    然后对第二棵树进行dfsdfs。对于一个点xx,我们先将他的所有子节点求出答案,每求完一个点的答案就把这个点在第一棵树中对应的编号位置aia_i记为1。那么xx与其子节点对答案的贡献就是i=LxRxaisum^{R_x}_{i=L_x}a_i
    时间复杂度O(nlogn)O(nlog n)


    代码:

    #include <cstdio>
    #include <cstring>
    using namespace std;
    
    const int N=100010;
    int n,tot,head[N],L[N],R[N];
    long long ans;
    
    struct edge
    {
    	int next,to;
    }e[N*2];
    
    struct BIT
    {
    	int c[N];
    	
    	void add(int x)
    	{
    		for (int i=x;i<=n;i+=i&-i)
    			c[i]++;
    	}
    	
    	int ask(int x)
    	{
    		int sum=0;
    		for (int i=x;i;i-=i&-i)
    			sum+=c[i];
    		return sum;
    	}
    }bit;
    
    void add(int from,int to)
    {
    	e[++tot].to=to;
    	e[tot].next=head[from];
    	head[from]=tot;
    }
    
    void dfs1(int x,int fa)
    {
    	L[x]=++tot;
    	for (int i=head[x];~i;i=e[i].next)
    		if (e[i].to!=fa) dfs1(e[i].to,x);
    	R[x]=tot;
    }
    
    void dfs2(int x,int fa)
    {
    	for (int i=head[x];~i;i=e[i].next)
    		if (e[i].to!=fa)
    		{
    			ans-=(long long)bit.ask(R[e[i].to])-bit.ask(L[e[i].to]);
    			dfs2(e[i].to,x);
    		}
    	ans+=(long long)bit.ask(R[x])-bit.ask(L[x]);
    	bit.add(L[x]);
    }
    
    int main()
    {
    	scanf("%d",&n);
    	memset(head,-1,sizeof(head));
    	for (int i=1,x,y;i<n;i++)
    	{
    		scanf("%d%d",&x,&y);
    		add(x,y); add(y,x);
    	}
    	tot=0; dfs1(1,0); tot=0;
    	memset(head,-1,sizeof(head));
    	for (int i=1,x,y;i<n;i++)
    	{
    		scanf("%d%d",&x,&y);
    		add(x,y); add(y,x);
    	}
    	dfs2(1,0);
    	printf("%lld
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    推荐三首适合午休时听的歌
    我要用全身心的爱来迎接每一天!
    过年,别忘了给父母买点东西
    外来务工的人们,你们真是不容易啊!
    新年最新的100句超牛的语言(转)
    最近Gmail扩容的很快
    老板其人
    乒乓爱好者请进:看看你是第几级?
    上海轨道交通地图电子版(提供下载)
    windows XP使用秘籍(包括空当接龙秘籍)
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998012.html
Copyright © 2011-2022 走看看