题解:P13259 [GCJ 2014 #2] Trie Sharding
测试点下载:测试点.zip
思路
第一问
考虑贪心。设
当前缀
考虑将输入字符串
第二问
考虑树形 dp。根据第一问的分析,最优分配会将每个前缀
接着看看怎么转移。对于节点
- 它的每个子节点都可以取任意中方案,所以
f_x 要乘上\Pi_{i\in son_x}f_i 。 - 还需要考虑把它子树内的字符串(在
s 中)分配到K_p 个服务器里的方案数。如果x 代表的字符串在s 中,则需要考虑把它子树内的字符串和它本身分配到K_p 个服务器里的方案数。 对于每个i\in son_x ,它字子树内K_i 个服务器的分配已经处理好了。现在只需要把这K_i 个服务器对应到K_p 个服务器就好了。这K_i 个服务器可以看成是相同的,但是不同子节点的K_i 个服务器则是不同的。可以看成将一个可重集L 里的元素分成K_p 类,每类不为空,方案数记作g\left(L,K_p\right) (g\left(L,K_p\right) 的求法后面再讲)。 - 对于
x 代表的字符串在s 中的情况,就多了x 这个元素分成K_p 类,在L 中多加一个元素即可。
现在计算
code
#include<bits/stdc++.h>
using namespace std;
const int mod=1000000007;
int C[105][105],f[105];
int g(vector<int> l,int k)
{
f[1]=1;
for(int j:l)f[1]=1LL*f[1]*C[1][j]%mod;
for(int i=2;i<=k;i++)
{
f[i]=1;
for(int j:l)f[i]=1LL*f[i]*C[i][j]%mod;
for(int j=1;j<i;j++)f[i]=(f[i]-1LL*f[j]*C[i][i-j]%mod+mod)%mod;
}
return f[k];
}
int n,k,ans1,ans2;
string s[1005];
struct hs{int operator()(char x){return x-'A';}};
template<int N,int M,class toInt>
class trie
{
toInt f;
int ch[N+5][M],cnt[N+5],dp[N+5],tot;
bool end[N+5];
public:void insert(string s)
{
int x=1;
cnt[x]++;
for(char i:s)
{
if(!ch[x][f(i)])ch[x][f(i)]=++tot;
x=ch[x][f(i)];
cnt[x]++;
}
end[x]=1;
}
int getans()
{
vector<int>L;
for(int i=tot;i>=1;i--)
{
L.clear();
dp[i]=1;
for(int j=0;j<M;j++)
if(ch[i][j])
dp[i]=1LL*dp[i]*dp[ch[i][j]]%mod,L.push_back(min(cnt[ch[i][j]],k));
if(end[i])L.push_back(1);
dp[i]=1LL*dp[i]*g(L,min(cnt[i],k))%mod;
}
return dp[1];
}
int size(){return tot;}
void clear()
{
memset(ch,0,sizeof ch);
memset(cnt,0,sizeof cnt);
memset(end,0,sizeof end);
tot=1;
}
trie():tot(1){}
};
trie<100000,26,hs>t,v;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
C[0][0]=1;
for(int i=0;i<=100;i++,C[i][0]=1)
for(int j=1;j<=i;j++)
C[i][j]=(C[i-1][j]+C[i-1][j-1])%mod;
int T;
cin>>T;
for(int Case=1;Case<=T;Case++)
{
cin>>n>>k;
ans1=ans2=0;
t.clear();
for(int i=1;i<=n;i++)cin>>s[i],t.insert(s[i]);
sort(s+1,s+n+1);
for(int i=1;i<=k;i++)
{
v.clear();
for(int j=i;j<=n;j+=k)v.insert(s[j]);
ans1+=v.size();
}
ans2=t.getans();
cout<<"Case #"<<Case<<": "<<ans1<<" "<<ans2<<endl;
}
return 0;
}