牛客 - 树上博弈(思维)

题目链接:点击查看

题目大意:给出一棵树,现在有两个人在玩一个游戏,两人依次在树上行走,只能走没有人的结点,无法行走的人失败,题目需要我们求出有多少个初始点对,对于先手而言是必胜的情况

题目分析:其实稍微画图就能看出来,如果初始时两个人之间的距离为偶数,那么先手必胜,否则先手必败,因为如果初始距离为偶数的话,那么先手总是可以有路可走的,而后手总会被逼到叶子结点上去,而距离为偶数,意味着深度奇偶性相同的结点,读入时记录一下奇偶性不同的结点有多少个,最后排列组合C( n , 2 )就是答案了,因为当两个点确定时,两人的位置还可以互换,所以最后结果需要乘以 2 

代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<unordered_map>
using namespace std;
    
typedef long long LL;
   
typedef unsigned long long ull;
    
const int inf=0x3f3f3f3f;
    
const int N=1e6+100;

int deep[N];

LL cnt[2];
 
int main()
{
//#ifndef ONLINE_JUDGE
//  freopen("input.txt","r",stdin);
//    freopen("output.txt","w",stdout);
//#endif
//  ios::sync_with_stdio(false);
    int n;
    scanf("%d",&n);
    deep[1]=0;
    cnt[0]++;
    for(int i=2;i<=n;i++)
    {
    	int fa;
    	scanf("%d",&fa);
    	deep[i]=deep[fa]^1;
    	cnt[deep[i]]++;
	}
	printf("%lld\n",cnt[0]*(cnt[0]-1)+cnt[1]*(cnt[1]-1));
     
     
     
     
     
       
       
       
       
       
       
       
    return 0;
}
发布了646 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/104272758