fzu 2218 Simple String Problem 状压dp

Problem 2218 Simple String Problem

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

4
25 5
abcdeabcdeabcdeabcdeabcde
25 5
aaaaabbbbbcccccdddddeeeee
25 5adcbadcbedbadedcbacbcadbc
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.

 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值