fzuoj 2218 Simple String Problem(狀態壓縮dp)

Problem 2218 Simple String Problem

Accept: 10    Submit: 40
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

425 5abcdeabcdeabcdeabcdeabcde25 5aaaaabbbbbcccccdddddeeeee25 5adcbadcbedbadedcbacbcadbc3 2aaa

 Sample Output

6150210

 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

第六屆福建省大學生程序設計競賽-重現賽(感謝承辦方華僑大學)

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

二進制狀態壓縮,每位的狀態表示第i個字母存在狀態,n^2的時可以枚舉出所有子串的狀態和長度。然後每次與(1<<k - 1)異或就是不含相同的子串

狀態。但是我開始想直接對每一種狀態枚舉他的子集和異或值,不過這太大了,肯定會超時,不過我們可以用dp[t]表示t狀態所有子集的最大長度

先狀態轉移一下,最後之間遍歷所有狀態和其異或狀態就可以更新出答案。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<map>
#include<vector>
#include<cstring>
#include<cmath>
#define eps 1e-12
using namespace std;
typedef long long ll;
const ll mo = 1000000007, N = 2*1e3+10;
char s[N];
int dp[(1<<16)+100];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n, m;
        scanf("%d%d", &n, &m);
        scanf("%s", s);
        memset(dp, 0, sizeof(dp));
        for(int i = 0; i<n; i++)
        {
            int t = 0;
            for(int j = i; j<n; j++)
            {
                t |= 1<<(s[j] - 'a');
                dp[t] = max(dp[t], j - i + 1);
            }
        }
        int s = 1<<m;
        for(int i = 0; i<s; i++)
        {
            for(int j = 0; j<m; j++)
            {
                if((1<<j) & i)
                    dp[i] = max(dp[i], dp[i^(1<<j)]);
            }
        }
        int ans = 0;
        for(int i = 0; i<s; i++)
        {
            ans = max(ans, dp[i]*dp[(s-1)^i]);
        }
        cout<<ans<<endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章