G - Simple String Problem
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit Status Practice FZU 2218
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=16; int dp[1<<16+5]; char str[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",str); for(int i=0;i<n;i++){//我们将16种字母划分为16位,直接dp[0~1<<16-1],对于每一位,如果值为0,代表那么字母不存在,如果为1 //代表那个字母存在, int t=0; for(int j=i;j<n;j++){ t|=1<<(str[j]-‘a‘); dp[t]=max(dp[t],j-i+1);//求出某种状态的最长序列,,, } } int s=1<<k; for(int i=0;i<s;i++){ for(int j=0;j<k;j++){ if(i&(1<<j))//这里从少的字符遍历到多的字符,迭代累加, dp[i]=max(dp[i],dp[i^(1<<j)]);//每次逐位进行比较,如果i字符串中包含地j个字符,那么更新dp值 } } int ans=0; for(int i=0;i<s;i++) ans=max(ans,dp[i]*(dp[(s-1)^i]));//calculate printf("%d\n",ans); } return 0; }