a548中等位元集合記錄不同子序列
CPE:License Plates (UVa 13257)
以字母組合去重,而不是累計位置選法。
解題思路
掃描字元 c 之前,seen 是已出現的單字母集合,pairs[b] 是已可形成 ab 的所有首字母 a。triples[b][c] 是已形成 abc 的首字母集合。看到 c 時,對每個 b 做 triples[b][c] |= pairs[b],用位元 OR 自動消除不同位置產生的同一字串。
接著更新 pairs[c] |= seen,最後把 c 加進 seen。必須先更新三字母、再雙字母、再單字母,才能保證三個選取位置嚴格遞增,不會重用當前字元。最後把26×26個位元集合的位元數相加;答案最多26³,短於3的字串自然為0。
Step-by-step animation
示意:字串 ABAB
步驟 1 / 3
前兩字
讀 A、B 後,seen={A,B},雙字母只有 AB。
seen:A,B
pairs[B]:A
- 不同三字母
- 0
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
uint32_t seen = 0;
array<uint32_t, 26> pairs{};
array<array<uint32_t, 26>, 26> triples{};
for (char ch : s) {
int c = ch - 'A';
for (int b = 0; b < 26; ++b)
triples[b][c] |= pairs[b];
pairs[c] |= seen;
seen |= uint32_t(1) << c;
}
int ans = 0;
for (auto &row : triples)
for (uint32_t mask : row)
while (mask) {
++ans;
mask &= mask - 1;
}
cout << ans << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。