fzu2188 状压dp

时间:2021-08-10 06:39:53
G - Simple String Problem

Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

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.

状压dp,解释在代码中注释掉了,自己看吧

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=;
int dp[<<+];
char str[];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,k;
memset(dp,,sizeof(dp));
scanf("%d%d",&n,&k);
scanf("%s",str);
for(int i=;i<n;i++){//我们将16种字母划分为16位,直接dp[0~1<<16-1],对于每一位,如果值为0,代表那么字母不存在,如果为1
//代表那个字母存在,
int t=;
for(int j=i;j<n;j++){
t|=<<(str[j]-'a');
dp[t]=max(dp[t],j-i+);//求出某种状态的最长序列,,,
}
} int s=<<k;
for(int i=;i<s;i++){
for(int j=;j<k;j++){
if(i&(<<j))//这里从少的字符遍历到多的字符,迭代累加,
dp[i]=max(dp[i],dp[i^(<<j)]);//每次逐位进行比较,如果i字符串中包含地j个字符,那么更新dp值
}
}
int ans=;
for(int i=;i<s;i++)
ans=max(ans,dp[i]*(dp[(s-)^i]));//calculate
printf("%d\n",ans); }
return ;
}