hdu 5677(manacher + 二维背包)

ztr loves substring

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)


Problem Description
ztr love reserach substring.Today ,he has n string.Now ztr want to konw,can he take out exactly k palindrome from all substring of these n string,and thrn sum of length of these k substring is L.

for example string "yjqqaq"
this string contains plalindromes:"y","j","q","a","q","qq","qaq".
so we can choose "qq" and "qaq".
 

Input
The first line of input contains an positive integer T(T<=10) indicating the number of test cases.

For each test case:

First line contains these positive integer N(1<=N<=100),K(1<=K<=100),L(L<=100) .
The next N line,each line contains a string only contains lowercase.Guarantee even length of string won't more than L.
 

Output
For each test,Output a line.If can output "True",else output "False".
 

Sample Input
  
  
3 2 3 7 yjqqaq claris 2 2 7 popoqqq fwwf 1 3 3 aaa
 

Sample Output
  
  
False True True
 

解题思路:首先用manacher算法把每个字符串的回文半径都算出来,接下来用一个vector把所有的回文串长度都记录下来。接下来就是dp部分:dp[i][j][k]表示在vector记录的序列中,在前i个数中选择j个,且此时总长度为k是否可行,dp是个bool数组。很明显,这是一个二维背包问题,利用滚动数组优化一下即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;

const int maxn = 105;
int n,k,m,r[maxn][maxn<<1];
char str[maxn][maxn],c[maxn<<1];
bool dp[maxn][maxn];
vector<int> vec;

void manacher(int len,int *r)
{
	int id = 0,maxlen = 0;
	r[0] = 1;
	for(int i = 1; i <= 2*len; i++)
	{
		if(r[id] + id > i) r[i] = min(r[2*id-i],r[id] + id - i);
		else r[i] = 1;
		while(c[i-r[i]] == c[i+r[i]]) r[i]++;
		if(r[i] + i > maxlen)
		{
			maxlen = r[i] + i;
			id = i;
		}
	}
}

void solve()
{
	memset(dp,false,sizeof(dp));
	dp[0][0] = true;
	for(int i = 0; i < vec.size(); i++)
		for(int j = k; j >= 1; j--)	
			for(int t = m; t >= vec[i]; t--)
				if(dp[j-1][t-vec[i]] == true)
					dp[j][t] = true;
	if(dp[k][m])
		printf("True\n");
	else printf("False\n");
}

int main()
{
	int t;
	cin >> t;
	while(t--)
	{
		cin >> n >> k >> m;
		vec.clear();
		for(int i = 1; i <= n; i++)
		{
			cin >> str[i] + 1;
			int len = strlen(str[i] + 1);
			memset(c,0,sizeof(c));
			c[0] = '@';
			for(int j = 1; j <= 2*len; j++)
			{
				c[2*j] = '#';
				c[2*j-1] = str[i][j];
			}
			c[2*len] = '$';
			manacher(len,r[i]);
			for(int j = 1; j <= 2*len; j++) //加入所有可能的回文串个数
			{
				int tmp = r[i][j];
				if(j % 2 == 0 && tmp == 1) continue;
				if(j % 2 == 1) tmp = (r[i][j]+1) / 2 * 2 - 1;
				else tmp = r[i][j] / 2 * 2;
				while(tmp > 0)
				{
					vec.push_back(tmp);
					tmp -= 2;
				}
			}
		}
		solve();
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值