Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C++ by paste ( 15 years ago )
/*
 * C.cpp
 *
 *  Created on: 21.01.2011
 *      Author: pasha
 */

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stdio.h>

using namespace std;
enum CHOICE
{
 INSERT, DELETE, REPLACE, NOTHING
};

const int MAX_INT = ~(1 << 31);

int main()
{
 freopen("d.in", "r", stdin);
 freopen("d.out", "w", stdout);
 string s;
 string t;
 cin >> s >> t;
 vector<vector<int> > dyn;
 vector<vector<int> > choice;

 dyn.assign(s.length() + 1, vector<int> (t.length() + 1, 0));
 choice.assign(s.length() + 1, vector<int> (t.length() + 1, 0));

 for (int i = 0; i <= (int) s.length(); i++)
 {
  dyn[i][0] = i;
  choice[i][0] = DELETE;
 }

 for (int i = 1; i <= (int) t.length(); i++)
 {
  dyn[0][i] = i;
  choice[0][i] = INSERT;
  for (int j = 1; j <= (int) s.length(); j++)
  {
   int min = MAX_INT;
   int cur_choice = NOTHING;
   if (dyn[j][i - 1] + 1 < min)
   {
    min = dyn[j][i - 1] + 1;
    cur_choice = INSERT;
   }
   if (dyn[j - 1][i] + 1 < min)
   {
    min = dyn[j - 1][i] + 1;
    cur_choice = DELETE;
   }
   if (s[j] == t[i] && dyn[j - 1][i - 1] < min)
   {
    min = dyn[j - 1][i - 1];
    cur_choice = NOTHING;
   }
   if (s[j] != t[i] && dyn[j - 1][i - 1] + 1 < min)
   {
    min = dyn[j - 1][i - 1] + 1;
    cur_choice = REPLACE;
   }
   dyn[j][i] = min;
   choice[j][i] = cur_choice;
  }
 }
 int ans;
 vector<char> ans_let;
 vector<int> ans_pos;
 vector<CHOICE> ans_ch;
 for (int s_i = s.length(), t_i = t.length(); dyn[s_i][t_i] != 0;)
 {
  ans++;
  switch (choice[s_i][t_i])
  {
  case INSERT:
  {
   ans_ch.push_back(INSERT);
   ans_let.push_back(t[t_i]);
   ans_pos.push_back(t_i + 1);
   t_i--;
  }
   break;
  case REPLACE:
  {
   ans_ch.push_back(REPLACE);
   ans_let.push_back(t[t_i]);
   ans_pos.push_back(t_i + 1);
   t_i--;
   s_i--;
  }
   break;
  case NOTHING:
  {
   t_i--;
   s_i--;
   ans--;
  }
   break;
  case DELETE:
  {
   ans_ch.push_back(DELETE);
   ans_let.push_back(0);
   ans_pos.push_back(t_i);
   s_i--;
  }
   break;
  }
 }
 reverse(ans_ch.begin(), ans_ch.end());
 reverse(ans_let.begin(), ans_let.end());
 reverse(ans_pos.begin(), ans_pos.end());
 cout << ans << 'n';
 for (int i = 0; i < ans; i++)
 {
  switch (ans_ch[i])
  {
  case INSERT:
  {
   cout << "INSERT" << " " << ans_pos[i] << " " << ans_let[i] << 'n';
  }
   break;
  case REPLACE:
  {
   cout << "REPLACE" << " " << ans_pos[i] << " " << ans_let[i] << 'n';
  }
   break;
  case DELETE:
  {
   cout << "REPLACE" << " " << ans_pos[i] << 'n';
  }
   break;
  }
 }
}

 

Revise this Paste

Your Name: Code Language: