Codeforces Round #393 (Div. 2) (8VC Venture Cup 2017 – Final Round Div. 2 Edition), problem: (F) Bacterial Melee Solution in C/C++

#include <bits/stdc++.h>
using namespace std;

const int mod = 1e9+7;

long long t[20000];

long long binpow(long long a, long long n){
long long ans = 1;
while(n){
if(n&1) ans = ans*a % mod;
a = a*a % mod;
n >>= 1;
}
return ans;
}

long long inv(long long x){
return binpow(x, mod-2);
}

long long c_n_k(long long n, long long k){
return t[n]*inv(t[k]) % mod * inv(t[n-k]) % mod;
}

const long long maxn = 5005, k = 26;

long long dp[maxn][maxn];

long long cnt[maxn];

long long p[maxn][k];

int main(){

t[0] = 1;
for(long long i = 1; i < 20000; i++)
t[i] = i*t[i-1] % mod;

long long n;
cin >> n;

string s;
cin >> s;

for(long long i = 0; i < k; i++)
p[n][i] = n;

for(long long i = n-1; i >= 0; i–){
memcpy(p[i], p[i+1], sizeof(p[i]));
p[i][s[i]-‘a’] = i;
}

for(long long i = 0; i < 26; i++)
dp[p[0][i]][1] = 1;

for(long long i = 0; i < n; i++){
p[i][s[i]-‘a’] = n;
for(long long l = 1; l <= n; l++){
dp[i][l] %= mod;
if(dp[i][l] == 0) continue;
for(long long j = 0; j < k; j++)
dp[p[i][j]][l+1] += dp[i][l];
cnt[l] = (cnt[l] + dp[i][l]) % mod;
}
}

long long ans = 0;

for(long long l = 1; l <= n; l++){
long long r = n-l;
ans = (ans + cnt[l]*c_n_k(r+l-1, r)) % mod;
}

cout << ans;

return 0;
}

(Visited 84 times, 1 visits today)

About the Author:

Leave A Comment