Created
May 6, 2015 13:04
-
-
Save jiunbae/a33bf4c0a12a13bc1ef2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<vector> | |
#include<algorithm> | |
#include<string> | |
#include<iostream> | |
using namespace std; | |
#pragma warning (disable : 4996) | |
template <typename type> type _max(type a, type b) | |
{ | |
return a > b ? a : b; | |
} | |
std::string str_a, str_b, str; | |
typedef struct { | |
int x, y; | |
}POINT; | |
int ary[1111][1111] = { 0, }; | |
int LCS(int x, int y) | |
{ | |
if (x < 0 || y < 0) | |
return 1; | |
else if (ary[x][y] == 0) | |
if (str_a[x] == str_b[y]) | |
return ary[x][y] = LCS(x-1,y-1)+1; | |
else | |
return ary[x][y] = _max<int>(LCS(x-1,y), LCS(x,y-1)) ; | |
else | |
return ary[x][y]; | |
} | |
POINT LCS_BACK(std::string * str, int x, int y) | |
{ | |
int dx[] = { 0, -1 ,-1}, dy[] = { -1, 0 ,-1}, dd = -1; | |
if (x < 0 || y < 0) | |
return{ -1, -1 }; | |
for (int i = 0; i < 2; i++) | |
if (ary[x][y] == ary[x + dx[i]][y + dy[i]]) | |
dd = i; | |
if (dd == -1) | |
{ | |
*str += str_a[x]; | |
dd = 2; | |
} | |
return{ x + dx[dd], y + dy[dd]}; | |
} | |
int main(int argc, char * argv[]) | |
{ | |
std::cin >> str_a >> str_b; | |
for (int i = 0; i < str_a.size(); i++) | |
for (int j = 0; j < str_b.size(); j++) | |
LCS(i, j); | |
std::cout << ary[str_a.size() - 1][str_b.size() - 1] - 1 << endl; | |
POINT p = {str_a.size()-1, str_b.size()-1}; | |
while ((p = LCS_BACK(&str, p.x , p.y )).x + 1); | |
std::reverse(str.begin(), str.end()); | |
std::cout << str; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment