Weak Subsequence
题目描述
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to kkk. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string sss if the length of string’s longest substring that is also its weak subsequence (see the definition given below) equals www.
String aaa with the length of nnn is considered the weak subsequence of the string sss with the length of mmm, if there exists such a set of indexes 1≤i1≤i2≤⋯≤in≤m1\le i_{1}\le i_{2}\le \cdots \le i_{n}\le m1≤i1≤i2≤⋯≤in≤m , that has the following two properties:
ak=sika_k = s_{ik}ak=sik for all k from 111 to nnn
there exists at least one such k(1≤k≤n)k (1 \le k \le n )k(1≤k≤n), for which ik+1–ik<1i_{k+1}–i_{k} < 1ik+1–ik<1
.
Petya got interested how many different strings are available for him to purchase in the shop.
解题:
一、先简单翻译一下
- 原始的字符串sss:长为nnn,由kkk个字母表里的字母组成;
- 子串aaa:长为mmm,是sss的子串;
- 若 子串aaa与字符串sss中的一个子序列相等,且aaa与iii至少有一个元素不同,则称子串aaa为弱子串。
- 题目目标是统计 最长的弱子串aaa 的长度 mmm 等于给定的值 www 的 原始字符串sss 的个数
二、找到弱子串存在的充要条件
弱子串aaa 的定义与字符串sss中的一个子序列有关,这是“存在”的关系。
我们定义字符串sss中子串aaa左侧为前缀为iii、右侧为后缀为jjj。我们发现,那么如果前缀iii中包含子串aaa的首字母,或者后缀jjj中包含子串aaa的尾字母,那么aaa一定为弱子串。
三、界定弱子串是是否最长,即,找到最长弱子串
我们对弱子串的判断,是借助前缀和后缀中是否包含子串的首尾字母来实现的,但这是定性的分析。我们对其做定量的分析。
首先,从条件上来看,只要前缀或后缀中,有一个首字母或尾字母就可以满足要求。
如果,存在两个以上的字母,我们可以将前缀中,第二个出现的字母往右并入子串,或者将后缀中,第一个出现的字母往左并入子串。此时该子串仍为弱子串,且长度增加。
这验证了两件事:
- 前缀或后缀中存在两个以上的首字母或尾字母,则当前子串并非最长;
- 最长的子串前缀或后缀中有且只有一个首字母或尾字母。
第二条是我们寻找最长弱子串的条件。
四、求最长弱子串的长度,然后计算所有可能性
长弱子串的长度 mmm = n−min(i,j)n - min(i, j)n−min(i,j), 其中i为前缀长,j为后缀长。
在满足条件的所有可能中,mmm的值为www,而nnn、iii、jjj的值受到
kkk的限制。分情况讨论前缀、后缀与中间子串的关系,即可求的答案