HDU 4628(动态规划-状压dp)

女爷i 2022-06-01 04:59 291阅读 0赞

问题描述:

You heart broke into pieces.My string broke into pieces.But you will recover one day,and my string will never go back.
Given a string s.We can erase a subsequence of it if this subsequence is palindrome in one step. We should take as few steps as possible to erase the whole sequence.How many steps do we need?
For example, we can erase abcba from axbyczbea and get xyze in one step.

Input

The first line contains integer T,denote the number of the test cases. Then T lines follows,each line contains the string s (1<= length of s <= 16).
T<=10.

Output

For each test cases,print the answer in a line.

Sample Input

  1. 2
  2. aa
  3. abb

Sample Output

  1. 1
  2. 2

题目题意:问最小次数可以删除整个串,每次删除只能是非连续的回文子串。

题目分析:首先我们先得求取所有的回文字串可能,然后就状压dp就好了 dp[i]表示到状态i的最小次数

代码如下:

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cmath>
  4. #include<string>
  5. #include<cstring>
  6. #include<vector>
  7. using namespace std;
  8. const int inf=1e9+7;
  9. string str;
  10. vector<int> vec;
  11. int dp[1<<16];
  12. bool check(int n)
  13. {
  14. vector<char > s;
  15. for (int i=0;i<16&&((1<<i)<=n);i++) {
  16. if (n&(1<<(i))) s.push_back(str[i]);
  17. }
  18. int left=0,right=s.size()-1;
  19. while (right>=left) {
  20. if (s[right]!=s[left]) return false;
  21. right--;
  22. left++;
  23. }
  24. return true;
  25. }
  26. void init(int n)
  27. {
  28. vec.clear();
  29. for (int i=1;i<(1<<n);i++) {
  30. if (check(i)) vec.push_back(i);
  31. }
  32. }
  33. int main()
  34. {
  35. int t;
  36. scanf("%d",&t);
  37. while (t--) {
  38. cin>>str;
  39. init(str.size());
  40. int len=str.size();
  41. for (int i=0;i<=((1<<len)-1);i++) {
  42. dp[i]=inf;
  43. }
  44. dp[0]=0;
  45. for (int i=0;i<=((1<<len)-1);i++) {
  46. if (dp[i]==inf) continue;
  47. for (int j=0;j<vec.size();j++) {
  48. if (!(i&(vec[j]))) {
  49. dp[i|vec[j]]=min(dp[i|vec[j]],dp[i]+1);
  50. }
  51. }
  52. }
  53. printf("%d\n",dp[(1<<len)-1]);
  54. }
  55. return 0;
  56. }

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读

    相关 POJ 1185(动态规划-dp)

    问题描述: 司令部的将军们打算在N\M的网格地图上部署他们的炮兵部队。一个N\M的地图由N行M列组成,地图的每一格可能是山地(用"H" 表示),也可能是平原(用"P"表示),

    相关 HDU 5691(动态规划-dp)

    问题描述: 度度熊是他同时代中最伟大的数学家,一切数字都要听命于他。现在,又到了度度熊和他的数字仆人们玩排排坐游戏的时候了。游戏的规则十分简单,参与游戏的N个整数将会做成一排