Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- string a, b;
- int dp[3005][3005];
- pair<int, int> backtrack[3005][3005];
- char bukva[3005][3005];
- int rek(int i, int j) {
- if(i < 0 or j < 0) {
- return 0;
- }
- if(dp[i][j] != -1) {
- return dp[i][j];
- }
- int result = 0;
- int r1 = -10, r2 = 0, r3 = 0;
- if(a[i] == b[j]) {
- r1 = rek(i - 1, j - 1) + 1;
- }
- r2 = rek(i - 1, j);
- r3 = rek(i, j - 1);
- result = max(r1, max(r2, r3));
- if(r3 == result) {
- backtrack[i][j] = make_pair(i, j - 1);
- bukva[i][j] = '.';
- }
- else if(r2 == result) {
- backtrack[i][j] = make_pair(i - 1, j);
- bukva[i][j] = '.';
- }
- else {
- backtrack[i][j] = make_pair(i - 1, j - 1);
- bukva[i][j] = a[i];
- }
- dp[i][j] = result;
- return result;
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cout.tie(0);
- cin.tie(0);
- cin >> a >> b;
- for(int i = 0; i < a.size(); i++) {
- for(int j = 0; j < b.size(); j++) {
- dp[i][j] = -1;
- }
- }
- if(rek((int) a.size() - 1, (int) b.size() - 1) == 0) {
- cout << "" << endl;
- return 0;
- }
- pair<int, int> p = make_pair(a.size() - 1, b.size() - 1);
- string s = "";
- while(true) {
- if(p.first >= 0 and p.second >= 0) {
- s += bukva[p.first][p.second];
- p = make_pair(backtrack[p.first][p.second].first, backtrack[p.first][p.second].second);
- }
- else {
- break;
- }
- }
- for(int i = (int) s.size() - 1; i >= 0; i--) {
- if(s[i] != '.') {
- cout << s[i];
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement