有一台特殊編輯器,支援三種操作:輸入字符、複製、刪除。給定一組字串集合,求輸入這些字串所需的最少按鍵次數(僅計算「輸入字符」操作)。
總按鍵數 = L₀ + Σ(len[i] - LCP(i-1, i)),其中 LCP 為最長公共前綴長度。1. 讀入測資筆數 T
2. 對每筆測資:
a. 讀入 n 及 n 個字串
b. 以 strcmp 升冪排序字串陣列
c. 計算首字串長度 + 累加後續字串「非共同前綴長度」
d. 輸出最小按鍵數與排序後字串順序(題目允許任意最優解)
O(n log n * L),L 為平均字串長度(≤100)。O(n * L)。#include <bits/stdc++.h>
using namespace std;
struct Word { char s[105]; };
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector<Word> w(n);
for (int i = 0; i < n; ++i) cin >> w[i].s;
sort(w.begin(), w.end(), [](const Word& a, const Word& b){
return strcmp(a.s, b.s) < 0;
});
int ans = strlen(w[0].s);
for (int i = 1; i < n; ++i) {
int k = 0;
while (w[i-1].s[k] && w[i-1].s[k] == w[i].s[k]) ++k;
ans += strlen(w[i].s) - k;
}
cout << ans << '\n';
for (auto &x : w) cout << x.s << '\n';
}
return 0;
}
while (w[i-1].s[k] && ...) 確保不越界。若操作成本不均勻(如複製成本 < 輸入成本),問題轉化為最短路徑/動態規劃,但本題等成本下貪心排序即為最優解。