AtCoder Grand Contest 021 D - Reversed LCS

Description

Takahashi has decided to give a string to his mother.
The value of a string T is the length of the longest common subsequence of T and T', where T' is the string obtained by reversing T. That is, the value is the longest length of the following two strings that are equal: a subsequence of T (possibly non-contiguous), and a subsequence of T' (possibly non-contiguous).
Takahashi has a string S. He wants to give her mother a string of the highest possible value, so he would like to change at most K characters in S to any other characters in order to obtain a string of the highest possible value. Find the highest possible value achievable.

题目大意:在改变原串最多K个字母的前提下,使得T和T的反串的LCS尽量长

Solution

猜个结论:T与T的反串的LCS等于T的最长回文子序列的长度
那么就做完了,做一个区间DP: 设 \(f[i][j][k]\) 表示区间 \([i,j]\) 修改了 \(k\) 次的最长的回文子序列的长度
分修改和不修改两种转移即可

#include<bits/stdc++.h>
using namespace std;
const int N=305;
int f[N][N][N],n,K;char s[N];
int main(){
  freopen("pp.in","r",stdin);
  freopen("pp.out","w",stdout);
  scanf("%s%d",s+1,&K);n=strlen(s+1);
  for(int i=1;i<=n;i++)
	  for(int k=0;k<=K;k++)f[i][i][k]=1;
  for(int len=2;len<=n;len++){
	  for(int i=1;i+len-1<=n;i++){
		  int j=i+len-1;
		  for(int k=0;k<=K;k++){
			  f[i][j][k]=max(f[i+1][j][k],f[i][j-1][k]);
			  if(s[i]==s[j])f[i][j][k]=max(f[i][j][k],f[i+1][j-1][k]+2);
			  if(k)f[i][j][k]=max(f[i][j][k],f[i+1][j-1][k-1]+2);
		  }
	  }
  }
  cout<<f[1][n][K]<<endl;
  return 0;
}

posted @ 2018-02-25 15:17  PIPIBoss  阅读(320)  评论(3编辑  收藏  举报