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;
}