Simple String Problem
Recently, you have found your interest in string theory. Here is an interesting question about strings.
You are given a string S of length n consisting of the first k lowercase letters.
You are required to find two non-empty substrings (note that substrings must be consecutive) of S, such that the two substrings don't share any same letter. Here comes the question, what is the maximum product of the two substring lengths?
Input
The first line contains an integer T, meaning the number of the cases. 1 <= T <= 50.
For each test case, the first line consists of two integers n and k. (1 <= n <= 2000, 1 <= k <= 16).
The second line is a string of length n, consisting only the first k lowercase letters in the alphabet. For example, when k = 3, it consists of a, b, and c.
For each test case, output the answer of the question.
4 25 5 abcdeabcdeabcdeabcdeabcde 25 5 aaaaabbbbbcccccdddddeeeee 25 5 adcbadcbedbadedcbacbcadbc 3 2 aaaSample Output
6 150 21 0Hint
One possible option for the two chosen substrings for the first sample is "abc" and "de".
The two chosen substrings for the third sample are "ded" and "cbacbca".
In the fourth sample, we can't choose such two non-empty substrings, so the answer is 0.
因为最多有16中字母,所以可以用dp状态压缩,用int中的前16位每为表示一个字母是否出现。先求出字母状态为i的最大长度dp[i]为多少,再求出dp[i]表示的字母状态i,及其子集的最大长度,更新dp[i],为什么求它的子集呢,因为首先子集状态的串可能比当前状态串要长,而且我们要求的两个子串没有相同的字母也就是两串01二进制串按位与为0,而其中一个串的子集状态只会在原有的1上变成0,所以它的子集状态与另一个串按位与仍然为0。所以要保存下它和它子集状态最长字符串,最后再用dp[i] * dp[s^i]求出最大值,s是全1状态和任何串异或后相当于全部取反正式我们想要的按位与为0的两个串。
code:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int dp[(1<<16)+10];
char s[2005];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,k;
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&k);
scanf("%s",s);
for(int i = 0; i < n; i++){
int m = 0;
for(int j = i; j < n; j++){//枚举子串记录每种状态的最长长度
m |= 1 << (s[j] - 'a');//更新状态
dp[m] = max(dp[m],j-i+1);
}
}
int s = (1 << k) - 1;
for(int i = 1; i <= s; i++){
for(int j = 0; j < k; j++){
if(i & (1 << j))//如果i状态中存在j位置的字符
dp[i] = max(dp[i],dp[i^(1<<j)]);//异或除去这个字符看i状态和其子集的最长长度
}
}
int ans = 0;
for(int i = 1; i <= s; i++){
int m = s ^ i;
ans = max(ans,dp[i] * dp[m]);
}
printf("%d\n",ans);
}
return 0;
}