题解 AGC064D

· · 题解

思路

记串中 B 的个数为 m。

考虑用 B 当做分隔符来考察每一对相邻 B 之间的 R 个数。

尝试刻画一次操作中 B 的相对位置对应的排列,显然每个 p_1=m 的排列 p 都是可以被取到的,构造方法就是把 x 贴到 pre(x) 后面。

然后再考虑每个 R 可以被丢到哪个位置,假设这个 R 在第 x 个 B 之后,那么我们可以发现此时所有 nxt(y)>x 的位置都仍然可以被贴。

于是问题转化为了一个非负整数序列 a 是好的,当且仅当:

直接 DP 即可,时间复杂度 O(n^3\log n)。

代码

// Problem: D - Red and Blue Chips
// Contest: AtCoder - AtCoder Grand Contest 064
// URL: https://atcoder.jp/contests/agc064/tasks/agc064_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
using namespace std;
inline int read(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}
mt19937_64 haitang(0520);
const int p=998244353;
int qp(int x,int y)
{
    int res=1;
    for(int t=x; y; y>>=1,t=1ll*t*t%p)
        if(y&1) res=1ll*res*t%p;
    return res;
}
int fac[1003],ifac[1003];
int f[303][303][303];
int a[1003];
char s[1003];
signed main()
{
    fac[0]=ifac[0]=1;
    for(int i=1; i<=1000; ++i)
        fac[i]=1ll*fac[i-1]*i%p,ifac[i]=qp(fac[i],p-2);
    int n=read(),m=0;
    scanf("%s",s+1);
    for(int i=1,z=0; i<=n; ++i)
        if(s[i]=='R') ++z;
        else a[++m]=z;
    for(int i=0; i<m; ++i) f[0][i][0]=ifac[i];
    for(int i=1; i<=n-m; ++i)
    {
        memcpy(f[i],f[i-1],sizeof(f[i-1]));
        for(int k=1; k<m; ++k)
            for(int l=i; l<=n-m; ++l)
            {
                int kk=k,ll=l,d=0;
                while(kk>=1&&ll>=i)
                {
                    if(a[kk]<ll) break;
                    --kk,ll-=i,++d;
                    f[i][k][l]=(f[i][k][l]+
                    1ll*f[i-1][kk][ll]*ifac[d])%p;
                }
            }
    }
    int ans=0;
    for(int i=0; i<=n-m; ++i) ans=(ans+1ll*f[n-m][m-1][i]*fac[m-1])%p;
    printf("%d\n",ans);
    return 0;
}