Codeforces 140E New Year Garland (dp + 容斥)

#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
using namespace std;  


#define inf 0x3f3f3f3f
#define N 5020
#define M 1000020
#define LL long long
#define mod 1000000007
#define ls (i << 1)
#define rs (ls | 1)
#define md (ll + rr >> 1)
#define lson ll, md, ls
#define rson md + 1, rr, rs
#define B 350


int Am[N], dp[N][N], f[N];
vector g[M];
int sum[M];

int n, m, p;
int a[M];

void init() {
	dp[0][0] = 1;
	for(int i = 1; i < N; ++i) {
		for(int j = 1; j <= i; ++j) {
			dp[i][j] = dp[i-1][j-1] + 1LL * dp[i-1][j] * (j - 1) % p;
			if(dp[i][j] >= p) dp[i][j] -= p;
		}
	}
	f[0] = 1;
	for(int i = 1; i < N; ++i) f[i] = 1LL * f[i-1] * i % p;
	Am[0] = 1;
	for(int i = 1; i <= m && i < N; ++i) Am[i] = 1LL * Am[i-1] * (m - i + 1) % p;
}

int main() {
	scanf("%d%d%d", &n, &m, &p);
	for(int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
		g[i].resize(a[i] + 1);
	}
	init();
	sum[0] = 1;
	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= a[i]; ++j) {
			g[i][j] = 1LL * sum[i-1] * dp[a[i]][j] % p * Am[j] % p;
			if(i > 1 && j <= a[i-1]) {
				g[i][j] -= 1LL * f[j] * g[i-1][j] % p * dp[a[i]][j] % p;
				if(g[i][j] < 0) g[i][j] += p;
			}
			sum[i] += g[i][j];
			if(sum[i] >= p) sum[i] -= p;
		}

	}

	printf("%d\n", sum[n]);
	return 0;
}

你可能感兴趣的:(codeforces,组合计数)