Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97526
  • 博文数量: 21
  • 博客积分: 145
  • 博客等级: 入伍新兵
  • 技术积分: 250
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-22 17:37
文章分类

全部博文(21)

文章存档

2013年(16)

2012年(5)

我的朋友

分类: C/C++

2013-04-03 22:18:10

原题:思路:这个问题其实等价于 求原来字符串 和 反向字符串最小编辑距离。
只是操作只有 删除、插入和copy。
删除: cost = 1
插入: cost = 1
copy: cost = 0

cost[i][j] = min {cost[i-1][j] + 1, cost[i][j-1] + 1}  if oriStr[i] <> revStr[i]
cost[i][j] = min {cost[i-1][j] + 1, cost[i][j-1] + 1, cost[i-1][j-1]}  if oriStr[i] == revStr[i]

上代码:

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>

  4. using namespace std;

  5. #define MAX 5001

  6. int cost[2][MAX];
  7. int length;
  8. string oriStr;
  9. string revStr;

  10. bool init() {
  11.     if (cin >> length) {
  12.         cin >> oriStr;
  13.         revStr = oriStr;
  14.         reverse(revStr.begin(), revStr.end());

  15.         return true;
  16.     }

  17.     return false;
  18. }

  19. int dp() {
  20.     for (int i=0; i<=length; i++)
  21.         cost[0][i] = i;
  22.     int cur, pre;

  23.     for (int i=1; i<=length; i++) {
  24.         cur = i % 2;
  25.         pre = (i + 1) % 2;
  26.         cost[cur][0] = i;
  27.         for (int j=1; j<=length; j++) {
  28.             int min = cost[cur][j-1] + 1;
  29.             if (cost[pre][j] + 1 < min)
  30.                 min = cost[pre][j] + 1;
  31.             if (oriStr[i-1] == revStr[j-1] && cost[pre][j-1] < min)
  32.                 min = cost[pre][j-1];
  33.             cost[cur][j] = min;
  34.         }
  35.     }
  36.     return cost[cur][length] / 2;
  37. }

  38. int main() {
  39.     while (init())
  40.         cout << dp() << endl;

  41.     return 0;
  42. }

阅读(568) | 评论(0) | 转发(0) |
0

上一篇:POJ1015解题报告

下一篇:C++ const总结

给主人留下些什么吧!~~