# Simple String Problem FZU - 2218 （状压dp）

## 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.

Output

For each test case, output the answer of the question.

Sample Input
4
25 5
abcdeabcdeabcdeabcdeabcde
25 5
aaaaabbbbbcccccdddddeeeee
25 5
3 2
aaa
Sample Output
6
150
21
0
Hint

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.

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;
}


• 评论

• 上一篇
• 下一篇