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.

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.

 

题意:给你一个串和两个整数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;
}

 

 

 

posted @ 2018-04-15 19:42  yzm10  阅读(329)  评论(0编辑  收藏  举报