FZU - 2218 Simple String Problem(狀壓dp)

Simple String Problem

Recently, you have found your interest in string theory. Here is an interesting question about strings.ui

You are given a string S of length n consisting of the first k lowercase letters.spa

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?rest


Input

The first line contains an integer T, meaning the number of the cases. 1 <= T <= 50.code

For each test case, the first line consists of two integers n and k. (1 <= n <= 2000, 1 <= k <= 16).blog

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

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".it

The two chosen substrings for the third sample are "ded" and "cbacbca".io

In the fourth sample, we can't choose such two non-empty substrings, so the answer is 0.class

 

題意:給你一個串和兩個整數n和k,n表示串的長度,k表示串只有前k個小寫字母,問你兩個不含相同元素的連續子串的長度的最大乘積。

第一道狀壓dp。詳見代碼。

 

 

#include<stdio.h> #include<string.h> #include<stdlib.h> #include<string> #include<math.h> #include<algorithm>
#define MAX 2005
#define INF 0x3f3f3f3f
using namespace std; typedef long long ll; int dp[(1<<16)+5];   //dp狀態存儲16個字母的存在狀況,1存在0不存在
int max(int x,int y){ return x>y?x:y; } int main() { int t,n,k,i,j; char s[MAX]; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&k); scanf(" %s",s); memset(dp,0,sizeof(dp)); for(i=0;i<n;i++){    //O(n^2)i首j尾遍歷字符串所有子串,在遍歷的同時每加入新字符須要及時更新狀態
            int tt=0; for(j=i;j<n;j++){ tt|=1<<(s[j]-'a');   //|=至關於加入s[j]字符
                dp[tt]=max(dp[tt],j-i+1);  //獲取含某幾種字符的子串最長長度
 } } //上一步僅僅是獲取了含某幾種字符的最長長度,還須要考慮子問題:好比某狀態有三種字符長度爲4,而另外一種狀態僅有其中的兩種字符長度就達到6,咱們要使兩個不含相同元素子串長度乘積最大,那麼在不會有重疊字符的前提下,長度固然越大越好,因此還要更新子問題
        for(i=0;i<(1<<k);i++){   //枚舉全部狀態
            for(j=0;j<k;j++){   //枚舉每種字符
                if(i&(1<<j)){   //若i狀態中有第j種字符
                    dp[i]=max(dp[i],dp[i^(1<<j)]);   //i狀態去掉j字符的子問題(異或異爲真,i^00000保持原狀,僅^含1位變0)
 } } } int maxx=0; for(i=0;i<(1<<k);i++){   //尋找最大值(1<<k-1爲k個1,i^11111每位所有取反,即爲尋找互補)
            maxx=max(maxx,dp[i]*dp[((1<<k)-1)^i]); } printf("%d\n",maxx); } return 0; }
相關文章
相關標籤/搜索