Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- int** new_matrix(int height, int width)
- {
- int** mx = new int* [height];
- for (int i = 0; i < height; i++)
- {
- mx[i] = new int[width];
- }
- return mx;
- }
- void reverseStr(string& str)
- {
- int n = str.length();
- for (int i = 0; i < n / 2; i++)
- {
- swap(str[i], str[n - i - 1]);
- }
- }
- int main()
- {
- ifstream IN;
- ofstream OUT;
- IN.open("input.txt");
- string str = "";
- getline(IN, str);
- IN.close();
- int n = str.length();
- int** matrix = new_matrix(n, n);
- for (int i = 0; i < n; i++)
- {
- matrix[i][i] = 1;
- }
- int s_j = 1;
- int j = 1;
- int i = 0;
- for (int k = 0; k < n; k++)
- {
- for (i; i < n; i++)
- {
- if (i + 1 == j)
- {
- if (str[i] != str[j])
- {
- matrix[i][j] = 1;
- }
- else
- {
- matrix[i][j] = 2;
- }
- }
- else if (i == j)
- {
- matrix[i][j] = 1;
- }
- else if (j > i)
- {
- if (str[i] != str[j])
- {
- if (matrix[i][j - 1] > matrix[i + 1][j])
- {
- matrix[i][j] = matrix[i][j - 1];
- }
- else
- {
- matrix[i][j] = matrix[i + 1][j];
- }
- }
- else
- {
- matrix[i][j] = matrix[i + 1][j - 1] + 2;
- }
- }
- if (j < n - 1)
- {
- j += 1;
- }
- }
- i = 0;
- if (j < n)
- {
- j = s_j + 1;
- s_j = j;
- }
- }
- int length = matrix[0][n - 1];
- i = 0;
- j = n - 1;
- string half_result_string = "";
- while (j >= i)
- {
- if (str[i] == str[j])
- {
- half_result_string += str[i];
- i += 1;
- j -= 1;
- }
- else
- {
- if (matrix[i][j - 1] > matrix[i + 1][j])
- {
- j -= 1;
- }
- else
- {
- i += 1;
- }
- }
- }
- string buffer = "";
- string final_string = "";
- if (length % 2 != 0)
- {
- buffer = half_result_string[length / 2];
- half_result_string = half_result_string.erase(half_result_string.length() - 1, 1);
- final_string += half_result_string;
- final_string += buffer;
- reverseStr(half_result_string);
- final_string += half_result_string;
- }
- else
- {
- final_string += half_result_string;
- reverseStr(half_result_string);
- final_string += half_result_string;
- }
- OUT.open("output.txt");
- OUT << length << "\n";
- for (int i = 0; i < length; i++)
- {
- OUT << final_string[i];
- }
- OUT.close();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement