a664困難唯一元素 LCS 轉為 LIS
CPE:Prince and Princess (UVa 10635)
利用路徑不重複格子的性質,避開平方級 LCS。
解題思路
將王子路徑的每個格子映射到它的出現位置 pos。依公主路徑順序掃描,只保留王子也走過的格子,換成 pos 序列。共同子序列必須在兩路徑中保持順序,因此恰好對應這串位置的嚴格遞增子序列。唯一格子的條件讓這個映射不會有重複匹配歧義。
用 tails[k] 保存長度 k+1 遞增子序列的最小結尾。對每個位置 x,二分找到第一個 ≥x 的尾端並取代,或接在最尾端;較小尾端永遠不會降低後續延伸能力。tails 的長度就是答案,起終點和其他格子同樣計數。每筆實際讀 p+1、q+1 個格子,輸出 Case k: L。
Step-by-step animation
示意:n=2,王子 1,2,4;公主 1,3,2,4
步驟 1 / 3
位置映射
公主的 3 不在王子路徑,轉換後是 0,1,2。
1→0
3→略過
2→1
4→2
- tails
- [0]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int tests;
cin >> tests;
for (int tc = 1; tc <= tests; tc++) {
int n, p, q;
cin >> n >> p >> q;
vector<int> pos(n * n + 1, -1), tails;
for (int i = 0; i <= p; i++) {
int x;
cin >> x;
pos[x] = i;
}
for (int i = 0; i <= q; i++) {
int x;
cin >> x;
x = pos[x];
if (x < 0)
continue;
auto at = lower_bound(tails.begin(), tails.end(), x);
if (at == tails.end())
tails.push_back(x);
else
*at = x;
}
cout << "Case " << tc << ": " << tails.size() << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。