Accept: 250 Submit: 580
Time Limit: 2000 mSec Memory Limit : 32768 KB
Problem 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
Sample Output
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.
Source
第六届福建省大学生程序设计竞赛-重现赛(感谢承办方华侨大学)题意: 给你一个由前k 个小写英文字符组成的字符串,然后你要找出两个子串 使得他们没有相同的 字符 然后 答案就是 两个子串长度的乘机。
思路: 状压dp 因为我们知道 k <= 16 那么我们就可以用 一个数的二进制的每一位去 表示该字符是否存在 ,那么我们用n方的复杂度就可以处理出来从 0000000 到 1111111 所有状态的所拥有的最大长度,, dp[ state ] 表示 state 状态下的含有 state 二进制 所对应的 字符的 子串的 最大长度, 但是再想 不仅要处理出state 状态下的 而且要处理出state 所有子集 状态下的最大长度 那么用 dp1[ state ] 表示state 所有子集 状态下 所对应的最大长度。 那么就可以用state 状态和1111111异或求得对面的状态 ,, 然后 dp1[state1]*dp[state2] 就是答案了。。。
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define N 2005
using namespace std;
int dp[(1<<16)+15];
int dp1[(1<<16)+15];
char str[N];
int n,k;
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>k;
memset(dp,0,sizeof(dp));
memset(dp1,0,sizeof(dp1));
scanf("%s",str+1);
for(int i=1;i<=n;i++) // 求出s 状态的 最大 len
{
int s=0;
for(int j=i;j<=n;j++)
{
int t= str[j] - 'a';
s=s|(1<<t);
dp[s]=max(dp[s],j-i+1);
}
}
int up=1<<k;
for(int i=0;i<up;i++) dp1[i]=dp[i];
for(int s=0;s<up;s++) // 求出s 状态的子集中的 最大 len
{
for(int j=0;j<k;j++)
{
if(s&(1<<j)){
int tmps=s-(1<<j);
dp1[s]=max(dp1[s],dp1[tmps]);
}
}
}
int ans=0;
for(int s=0;s<up;s++)
{
int tmps=((1<<k)-1)^s;
ans=max(ans,dp1[s]*dp1[tmps]);
}
cout<<ans<<endl;
}
return 0;
}