📌  相关文章
📜  具有相同左右旋转的数字的最长子序列的C ++程序(1)

📅  最后修改于: 2023-12-03 15:22:35.495000             🧑  作者: Mango

具有相同左右旋转的数字的最长子序列的C ++程序

这个C ++程序能够找到给定序列中的具有相同左右旋转的数字的最长子序列。这个程序可以用于密码学中的某些算法,例如哈希。下面是程序的代码片段:

#include <iostream>
#include <vector>

using namespace std;

int findLongestLRSequence(const vector<int>& sequence) {
    int n = sequence.size();

    // Find reverse of the sequence
    vector<int> reverseSequence(n, 0);
    for (int i = 0; i < n; i++) {
        reverseSequence[n - i - 1] = sequence[i];
    }

    // Create a vector to store the lengths of the longest sequences
    // ending at each index of the original and reversed sequences
    vector<int> longestLRSequence(n, 1);
    vector<int> longestRLSequence(n, 1);

    // Compute the lengths of the longest sequences ending at each index of
    // the original sequence
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (sequence[i] == sequence[j]) {
                longestLRSequence[i] = max(longestLRSequence[i], longestLRSequence[j] + 1);
            }
        }
    }

    // Compute the lengths of the longest sequences ending at each index of
    // the reversed sequence
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (reverseSequence[i] == reverseSequence[j]) {
                longestRLSequence[i] = max(longestRLSequence[i], longestRLSequence[j] + 1);
            }
        }
    }

    // Find the length of the longest sequence that is the same when read
    // forward and backward
    int longestSequence = 0;
    for (int i = 0; i < n; i++) {
        longestSequence = max(longestSequence, min(longestLRSequence[i], longestRLSequence[n - i - 1]));
    }

    return longestSequence;
}

int main() {
    vector<int> sequence = {1, 3, 2, 4, 2, 3, 1};
    int longestSequence = findLongestLRSequence(sequence);
    cout << "The length of the longest sequence that is the same when read" << endl;
    cout << "forward and backward is " << longestSequence << endl;
    return 0;
}

这个程序使用动态规划的方法来找到具有相同左右旋转的数字的最长子序列。该程序首先找到原序列的反向序列,并计算原序列和反向序列各自的最长递增子序列。然后,该程序找到两个序列中每个索引处的最长递增子序列的长度,并找到具有相同左右旋转的数字的最长子序列。