[思维]Factorial Divisibility Codeforces1754D

该博客探讨了一道编程题目,涉及计算数组元素阶乘之和是否能被给定数的阶乘整除。通过分析不等式1*1!+2*2!+......+n*n!<(n+1)!,并利用桶计数法简化计算,最终确定模x!的余数。代码实现中,通过检查阶乘计数是否存在非零项来判断整除性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given an integer xx and an array of integers a1,a2,…,ana1,a2,…,an. You have to determine if the number a1!+a2!+…+an!a1!+a2!+…+an! is divisible by x!x!.

Here k!k! is a factorial of kk — the product of all positive integers less than or equal to kk. For example, 3!=1⋅2⋅3=63!=1⋅2⋅3=6, and 5!=1⋅2⋅3⋅4⋅5=1205!=1⋅2⋅3⋅4⋅5=120.

Input

The first line contains two integers nn and xx (1≤n≤5000001≤n≤500000, 1≤x≤5000001≤x≤500000).

The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤x1≤ai≤x) — elements of given array.

Output

In the only line print "Yes" (without quotes) if a1!+a2!+…+an!a1!+a2!+…+an! is divisible by x!x!, and "No" (without quotes) otherwise.

题意: 给出n和x,接下来给出长度为n的数组a,问a[1]!+a[2]!+......+a[n]!是否是x!的倍数。

分析: 首先要知道一个不等式1*1!+2*2!+3*3!+......+n*n! < (n+1)!,这个不等式证明只需要把n*n!移到不等号右边,不断迭代最后剩下1*1! < 2*2!,因此显然成立。之后开一个500000的桶数组cnt,cnt[i]用来记录i这个阶乘出现的次数,之后对于i从1到x-1,将cnt[i]转为小于等于i的数,也就是如果i!每出现了i+1次就将其凑成一个(i+1)!,这样i!最后剩下个数一定小于等于i,这么处理完之后a[1]!+a[2]!+......+a[n]!就变成了k*x!加上某些位置m*i!(m小于等于i),而某些位置m*i!(m小于等于i)的加和根据上面的不等式可以知道是小于x!的,所以这些数加和模x!一定不为0,而k*x!模x!一定为0,也就是只要i从1到x-1中出现了一个非零的cnt[i],那么最后一定模x!不为0,最后只需要判断cnt在1到x-1内是否全0即可。

具体代码如下:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;

int cnt[500005];

signed main(){
	int n, x;
	cin >> n >> x;
	for(int i = 1; i <= n; i++){
		int t;
		scanf("%d", &t);
		cnt[t]++;
	} 
	for(int i = 0; i < x; i++){
		cnt[i+1] += cnt[i]/(i+1);
		cnt[i] %= (i+1);
	}
	bool flag = true;
	for(int i = 0; i < x; i++){
		if(cnt[i]){
			flag = false;
			break;
		}
	}
	if(flag) puts("Yes");
	else puts("No");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值