mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-09-05 17:50:36 +00:00
refactor: 重命名变量以提高代码可读性 将max_len改为maxlen,predecessor_k改为pk,max_lcsis改为maxlen,end_j改为endj,result_stack改为res,curr_i改为curri,curr_j改为currj chore: 移动sort-matrix-by-diagonals.cpp文件位置 从src/8/27/移动到src/8/28/并更新内容
94 lines
2.0 KiB
C++
94 lines
2.0 KiB
C++
#include <iostream>
|
|
#include <stack>
|
|
#include <vector>
|
|
|
|
using pii = std::pair<int, int>;
|
|
using ll = long long;
|
|
|
|
int main() {
|
|
std::ios_base::sync_with_stdio(false);
|
|
std::cin.tie(nullptr);
|
|
|
|
int n, m;
|
|
std::cin >> n;
|
|
std::vector<ll> a(n + 1);
|
|
for (int i = 1; i <= n; ++i)
|
|
std::cin >> a[i];
|
|
|
|
std::cin >> m;
|
|
std::vector<ll> b(m + 1);
|
|
for (int i = 1; i <= m; ++i)
|
|
std::cin >> b[i];
|
|
|
|
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0));
|
|
|
|
std::vector<std::vector<pii>> path(n + 1, std::vector<pii>(m + 1, {0, 0}));
|
|
|
|
for (int i = 1; i <= n; ++i) {
|
|
|
|
int maxlen = 0;
|
|
|
|
int pk = 0;
|
|
|
|
for (int j = 1; j <= m; ++j) {
|
|
|
|
dp[i][j] = dp[i - 1][j];
|
|
path[i][j] = {i - 1, j};
|
|
|
|
if (a[i] == b[j]) {
|
|
if (maxlen + 1 > dp[i][j]) {
|
|
dp[i][j] = maxlen + 1;
|
|
path[i][j] = {i - 1, pk};
|
|
}
|
|
}
|
|
|
|
if (b[j] < a[i]) {
|
|
if (dp[i - 1][j] > maxlen) {
|
|
maxlen = dp[i - 1][j];
|
|
pk = j;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int maxlen = 0;
|
|
int endj = 0;
|
|
|
|
for (int j = 1; j <= m; ++j) {
|
|
if (dp[n][j] > maxlen) {
|
|
maxlen = dp[n][j];
|
|
endj = j;
|
|
}
|
|
}
|
|
|
|
std::cout << maxlen << "\n";
|
|
|
|
if (maxlen > 0) {
|
|
std::stack<ll> res;
|
|
int curri = n;
|
|
int currj = endj;
|
|
|
|
while (curri > 0 && currj > 0) {
|
|
pii prev = path[curri][currj];
|
|
|
|
if (dp[curri][currj] > dp[prev.first][prev.second] && prev.second != currj) {
|
|
res.push(a[curri]);
|
|
}
|
|
|
|
curri = prev.first;
|
|
currj = prev.second;
|
|
}
|
|
|
|
bool first = true;
|
|
while (!res.empty()) {
|
|
if (!first) {
|
|
std::cout << " ";
|
|
}
|
|
std::cout << res.top();
|
|
res.pop();
|
|
first = false;
|
|
}
|
|
std::cout << "\n";
|
|
}
|
|
}
|