题解:P16590 [GKS 2016 #D] Codejamon Cipher

· · 题解

题解:P16590 [GKS 2016 #D] Codejamon Cipher

思路

容易发现单词打乱后字母频数不变,加密串是若干单词频数串的拼接。

可以想到预处理:对每个单词统计 26 个字母的频数,编码为字符串 key,存入哈希表 mp[key]。

考虑动态规划:设 dp[i] 表示前 i 个字符的方案数。
对每个i,枚举最后一段长度 len,维护当前段的频数 cnt,查表得单词个数 k ,转移 dp[i]=\sum_{len=1}^{20} dp[i-len]\times k。 答案即为:dp[n]\bmod 10^9+7。

代码

#include<bits/stdc++.h>
//Things will always be better, just let time play
using namespace std;
#define HACKILLER_FAST ios::sync_with_stdio(false),cin.tie(0)
#define int long long
#define rint register int
#define db double
#define pii pair<int,int>
#define vc vector
#define pb push_back
#define ls x<<1
#define rs x<<1|1
const int mod = 1e9+7;
int T,v,s,cnt[30],dp[4050];
string w;
vc<int> ans;

signed main(){
//  freopen("data.in","r",stdin);
//  freopen("task.out","w",stdout);
    HACKILLER_FAST;
    cin>>T;
    for(int t = 1;t <= T;++t){
        cin>>v>>s;
        unordered_map<string,int> mp;
        for(int i = 1;i <= v;++i){
            cin>>w;
            for(int j = 0;j < 26;++j) cnt[j] = 0;
            for(int j = 0;j < w.size();++j) cnt[w[j]-'a']++;
            string key(26,0);
            for(int j = 0;j < 26;++j) key[j] = cnt[j];
            mp[key]++;
        }
        ans.clear();
        while(s--){
            cin>>w;
            int n = w.size();
            memset(dp,0,sizeof(dp));
            dp[0] = 1;
            for(int i = 1;i <= n;++i){
                for(int j = 0;j < 26;++j) cnt[j] = 0;
                for(int len = 1;len <= 20 && len <= i;++len){
                    cnt[w[i-len]-'a']++;
                    string key(26,0);
                    for(int j = 0;j < 26;++j) key[j] = cnt[j];
                    auto it = mp.find(key);
                    if(it != mp.end()) dp[i] = (dp[i]+dp[i-len]*it->second)%mod;
                }
            }
            ans.pb(dp[n]%mod);
        }
        cout<<"Case #"<<t<<":";
        for(int x : ans) cout<<' '<<x;
        cout<<'\n';
    }
    return 0;
}
//地球毁灭了以后
//我仍爱你爱得 不知天高地厚
//为你再造一个 新宇宙
//不死之身 不灭的温柔

/*
Code by HACKILLER
Wish for
99
*/ //six seven