Counting of Trees AtCoder - 5633

Counting of Trees

Problem Statement

Given is an integer sequence D1,…,DN of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

  • For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is Di.

Notes

  • A tree of N vertices is a connected undirected graph with N vertices and N−1 edges, and the distance between two vertices are the number of edges in the shortest path between them.
  • Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

  • 1≤N≤105
  • 0≤DiN−1

Input

Input is given from Standard Input in the following format:

N
D1 D2 … DN

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24

题意:就是给出一串序列,每个数字代表到第一棵树的距离,求出树的所有可能的排列个数。

思路:首先判定树是否合法:第一个数字一定是0,并且所有树的距离,中间不能有中断,必须1-2-3-4-5-6....

肯定是树的每层的可能的排列数的乘积。

但是每层树的排列数我一开始错误的认为比如样例3中第三层应该是A34(3   4的全排列),但是A34的结果是6,实际排列数应该是8,2的3次方emmmmm(我一开始默认为二叉树的排列了。。)可以存在一棵树与两棵以上的树相连的。

所以就是每层的树的下一层树的次幂的乘积。

2000ms的题我补题都能tle。。。加了O2优化才过的(不晓得AtCoder能不能用嗷)

#pragma GCC optimize(2) 
#include<iostream>

using namespace std;
const int mod=998244353;
long long a[100010];
long long n,x;
long long ksm(long long a,long long b){
	long long res=1;
	while(b){
		if(b&1){
			res*=a;
			res%=mod;
		}
		a*=a;
		a%=mod;
		b>>=1;
	}
	return res;
}

int main(){
//	ios::sync_with_stdio(0);
//	cin.tie(0),cout.tie(0);
	scanf("%lld",&n);
	int flag=0;
	scanf("%lld",&x);
	int ans=x;
	if(x!=0) flag=1;
	for(int i=1;i<n;i++){
		scanf("%lld",&x);
		a[x]++;
		if(x==0) flag=1;
		if(x>ans){
			ans=x;
		}
	}
	
	if(flag){
		printf("0\n");
	}
	else{
	long long sum=1;
		for(int i=1;i<ans;i++){
			if(a[i]==0){
				flag=1;
				break;
			}
			sum*=ksm(a[i],a[i+1]);
			sum%=mod;
//			cout<<"SUM:"<<sum<<endl;
		}
		if(flag) printf("0\n");
		else printf("%lld\n",sum);
	}
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值