下面把押韵称为配对。
将字符串翻转可以把问题转化为前缀的问题。考虑 Trie。对所有字符串建出 Trie 树,我们考虑贪心。
性质:如果有两个字符串配对,那么在可能的情况下,应当选尽量长的前缀。这是因为,如果选比较短的,可能会和其它字符串冲突。
所以,对 Trie 树做 dfs,能在尽量深的地方配对就配对,不能就留到父节点配对。所以 dfs 有两个返回值:一个是目前还有多少个字符串没有配对,另一个是已经配对了多少个字符串。当然可以省略其中一个,但是为了便于理解就都存了,这题又不卡常。
dfs 大概是这样的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| pair<int, int> dfs(node *rt, bool isr = true) { int sz = rt->cnt; pair<int, int> ans; for(const auto &[_, ch] : rt->ch) { auto res = dfs(ch, false); ans.second += res.second; sz += res.first; delete ch; } rt->cnt = 0; rt->ch.clear(); if(!isr) { if(sz >= 2) { ans.second += 2; ans.first = sz - 2; } else ans.first = sz; } return ans; }
|
总代码&提交记录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <cstdio> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <map> #include <unordered_map> #include <utility>
using namespace std;
class node { public: int cnt = 0; map<char, node *> ch; } *rt = new node;
void insert(const string &str) { auto root = rt; for(char ch : str) { if(root->ch.count(ch)) root = root->ch[ch]; else root = root->ch[ch] = new node; } root->cnt++; }
pair<int, int> dfs(node *rt, bool isr = true) { int sz = rt->cnt; pair<int, int> ans; for(const auto &[_, ch] : rt->ch) { auto res = dfs(ch, false); ans.second += res.second; sz += res.first; delete ch; } rt->cnt = 0; rt->ch.clear(); if(!isr) { if(sz >= 2) { ans.second += 2; ans.first = sz - 2; } else ans.first = sz; } return ans; }
int main() { #ifndef ONLINE_JUDGE freopen("753294E.in", "r", stdin); freopen("753294E.out", "w", stdout); #endif int t; scanf("%d", &t); for(int v = 1; v <= t; v++) { int n; scanf("%d", &n); for(int i=1;i<=n;i++) { string str; cin >> str; reverse(str.begin(), str.end()); insert(str); } printf("Case #%d: %d\n", v, dfs(rt).second); } return 0; }
|
rec。
::anti-ai[同时,因为这是外星诗歌,所以 CODEJAM 是外星文。]