天天看點

Simple String Problem (狀壓dp)

https://cn.vjudge.net/contest/312854#problem/I

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

題意:給定一個字元串,由前k個小寫字母組成,取兩個子串,其中一個子串内的字母不與另一個子串内任何字母相同,求最大長度積。

分析:k最大16,狀壓的重要标志

将子串中字母種類的狀态壓縮,先求該狀态的最大子串長度,再将該狀态與該狀态的子狀态的最大子串長度取最大值

我們最後取長度積的時候肯定是讓該狀态與其補狀态相乘,但是可能該狀态的子狀态的值更大一些,用這個子狀态的值與其補狀态相乘也是合法的(一個子串内的字母不與另一個子串内任何字母相同) 比如說dp[000111]=3,dp[000011]=4,dp[111000]=3

#include<cstdio>
#include<algorithm>
#include<cstring>
#pragma GCC optimize(3)
#define max(a,b) a>b?a:b
using namespace std;
typedef long long ll;
const int N=2e3+5;
char s[N];
int dp[1<<16];
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
    	memset(dp,0,sizeof(dp));
    	int n,k;
    	scanf("%d%d",&n,&k);
    	scanf("%s",s);
    	for(int i=0;i<n;i++){ //n^2枚舉所有子串狀态 
    		int sta=0;
    		for(int j=i;j<n;j++){
    			sta|=(1<<(s[j]-'a'));
    			dp[sta]=max(dp[sta],j-i+1);//sta狀态所能達到的最大長度 
			}
		}
		int up=1<<k;
		for(int i=0;i<up;i++){//求出字母種類小于等于目前狀态所能達到的最大值
			for(int j=0;j<k;j++){
				if(i&(1<<j)){
					int sta=i^(1<<j);
					dp[i]=max(dp[i],dp[sta]); 
				}
			}
		} 
		int ans=0;
		for(int i=0;i<up;i++) ans=max(ans,dp[i]*dp[(up-1)^i]);
		printf("%lld\n",ans); 
	}
	return 0;
}