This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ll long long
const ll MOD = 1e9+7LL;
const int MAX = 4010;
using namespace std;
int N, M;
int qtdMod[MAX], moduloHere[MAX];
ll dp[MAX][MAX][2]; //flag pra falar se devo escolher livres ou duplas
ll bin[MAX][MAX];
ll fat[MAX], pot[MAX];
void calcBin(){
bin[0][0] = 1;
for(int i = 1; i <= 2*N; i++){
bin[i][0]=1;
for(int j = 1; j <= 2*N; j++){
bin[i][j] = (bin[i-1][j]+bin[i-1][j-1]);
if(bin[i][j] >= MOD)
bin[i][j] -= MOD;
}
}
}
void calcFat(){
fat[0] = 1;
for(int i = 1; i <= 2*N; i++)
fat[i] = (fat[i-1] * i) % MOD;
}
void calcPot(){
pot[0] = 1;
for(int i = 1; i <= 2*N; i++)
pot[i] = (pot[i-1] << 1LL) % MOD;
}
int getQuantity(int x){
return qtdMod[moduloHere[x]%M]-x;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M;
calcBin();
calcFat();
calcPot();
for(int i = 0; i < 2*N; i++)
qtdMod[i%M]++;
int ant = 0;
for(int i = 0; i < M; i++){
for(int q = qtdMod[i]; q > 0; q--,ant++ )
moduloHere[ant] = i;
}
for(int i = 1; i < M; i++)
qtdMod[i] += qtdMod[i-1];
dp[2*N][0][0] = dp[2*N][0][1] = 1;
for(int i = 2*N-1; i >= 0; i--)
for(int j = 0; j <= min(i,N); j++){
int foram = ((i-j)>>1)+j;
if(foram > N)
continue;
int faltam = N-foram;
int qtdModLeft = getQuantity(i);
if(faltam >= qtdModLeft){
ll jeito = (bin[faltam][qtdModLeft] * fat[qtdModLeft] ) % MOD;
jeito *= pot[qtdModLeft];
jeito %= MOD;
ll qMod = qtdMod[moduloHere[i]]-(moduloHere[i] == 0 ? 0 : qtdMod[moduloHere[i]-1]);
qMod = bin[qMod][qtdModLeft];
(jeito *= qMod) %= MOD;
dp[i][j][1] = jeito * dp[qtdMod[moduloHere[i]]][j+qtdModLeft][0];
dp[i][j][1] %= MOD;
}
dp[i][j][0] = dp[i][j][1];
if(j){
dp[i][j][0] += ( dp[i+1][j-1][0] * j ) % MOD;
if(dp[i][j][0] >= MOD)
dp[i][j][0] -= MOD;
}
}
cout << dp[0][0][0] << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |