设计密码 - 题目简述:
-
给定一个模式串 ,要求构造一个长度为 的字符串 ,使得字符串 不包含子串 ,问满足要求的字符串 的方案数
-
数据范围:
思路分析:
- 对于模式串匹配即 的过程,回顾 算法中数组 表示匹配串中以 结尾的子串与模式串的前缀可以匹配的最大长度,考虑只要 ,就说明以 结尾的子串不包含模式串
-
状态设计: 表示对于字符串 第 个字符, 匹配到第 个位置的方案数,即
-
考虑状态转移,对于已知的 ,枚举第 位填字符 ,并对字符 继续进行 匹配得到 ,则有:
-
答案统计:
Code:
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
const int N=60;
int n;
char str[N];
int nxt[N],f[N][N]; //写到密码串第 i 个字符,且当前 kmp 跳到 的第 j 状态(即 f[i]=j )的方案数
int main() {
scanf("%d%s",&n,str+1);
int len=strlen(str+1);
for(int i=2,j=0; i<=len; i++) {
while(j>0 && str[i]!=str[j+1]) j=nxt[j];
if(str[i]==str[j+1]) j++;
nxt[i]=j;
}
f[0][0]=1;
for(int i=0; i<n; i++)
for(int j=0; j<len; j++)
for(char k='a'; k<='z'; k++) {
int t=j;
while(t>0 && k!=str[t+1]) t=nxt[t];
if(k==str[t+1]) t++;
if(t<len) f[i+1][t]=(f[i+1][t]+f[i][j])%mod;
}
int ans=0;
for(int i=0; i<len; i++) ans=(ans+f[n][i])%mod;
printf("%d",ans);
return 0;
}修复DNA - 题目简述:
-
给定 个模式串 ,以及一个字符串 ,要求进行若干次修改使得字符串 不包含任意子串 ,问最小化修改次数
-
数据范围:
思路分析:
- 对于多模式串匹配即 自动机 的过程,所以只需要字符 串在 树上匹配不到匹配点
-
状态设计: 表示对于字符串 第 个字符,在 树上匹配到第 个节点且从未匹配到匹配点的最小修改次数
-
状态转移:
-
答案统计:
Code:
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
const int N=1010;
int n,t,f[N][N*4];
char str[N];
map<char,int> mp;
struct node {
int son[4];
int fail;
}trie[N*4];
bool ed[N*4];
int tot;
void Insert(char str[]) {
int len=strlen(str+1),p=0;
for(int i=1; i<=len; i++) {
int ch=mp[str[i]];
if(!trie[p].son[ch]) trie[p].son[ch]=++tot;
p=trie[p].son[ch];
}
ed[p]=1;
}
queue<int> q;
void make_fail() {
for(int i=0; i<4; i++) if(trie[0].son[i]) q.push(trie[0].son[i]);
while(!q.empty()) {
int x=q.front(); q.pop();
ed[x]|=ed[trie[x].fail];
for(int i=0; i<4; i++) {
int y=trie[x].son[i];
int Fail=trie[x].fail;
if(!y) trie[x].son[i]=trie[Fail].son[i];
else trie[y].fail=trie[Fail].son[i],q.push(y);
}
}
}
void init() {
memset(trie,0,sizeof(trie));
tot=0;
memset(ed,0,sizeof(ed));
memset(f,inf,sizeof(f));
}
int main() {
mp['A']=0,mp['C']=1,mp['G']=2,mp['T']=3;
while(scanf("%d",&n) && n!=0) {
init();
for(int i=1; i<=n; i++) {
scanf("%s",str+1);
Insert(str);
}
make_fail();
scanf("%s",str+1);
int len=strlen(str+1);
f[0][0]=0;
for(int i=0; i<len; i++)
for(int j=0; j<=tot; j++) {
if(ed[j] || f[i][j]==inf) continue;
for(int k=0; k<4; k++) {
int p=trie[j].son[k];
if(ed[p]) continue;
f[i+1][p]=min(f[i+1][p],f[i][j]+(mp[str[i+1]]!=k));
}
}
int ans=inf;
for(int i=0; i<=tot; i++)
ans=min(ans,f[len][i]);
printf("Case %d: %d\n",++t,ans==inf?-1:ans);
}
return 0;
}练习题:文本生成器
- 设计密码的多模式串匹配扩展
思维拓展:
- 这两篇题解的时间复杂度大致为 , 表示字符集大小,思考在设计密码问题的基础上,甚至拓展到多模式串匹配,对于字符串 应该如何解决呢,详解见此