跳到正文

题解

题解:P13108 [GCJ 2019 #1A] Alien Rhyme

Damon_cute约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月8日
更新
2026年7月14日
篇幅
约 5 分钟
获赞
2
题目
P13108

版本

  1. v2当前
  2. v1

题意

题目

定义两个字符串是押韵的表示两个字符串从重音字母开始的后缀相同,例如:PROL 和 TARPOL 是押韵的,但 PROL 和 TARPOL 不押韵。(粗体为重音字母)

给定 NN 个字符串 W1∼nW_{1 \sim n},你要给每个字符串划一个重音字母,并将其两两成对,使每一对两个字符串是押韵的,而不存在两字符串押韵但在不同的对。

思路

存储

Trie 树,但是 Trie 树存储共享的是前缀,所以我们要倒序存储。

例如:输入字符串为 eba,fba,ca,da,存储如下图:

在此图中 3,4,5,63, 4, 5, 6 节点为字符串的起点(或者说是存的终点)。

DFS

由于根节点(00 节点)对应单词没有实际的长度,所以 DFS 的起点应为根节点的子节点(此样例为 11)。

发现:令它们的重音字母如下:eba,fba,ca,da,则四个都可以两两成对,但如果这样:eba,fba,ca 和 da 就没有办法成对了,所以对于两个字符串,它们若要两两成对,最好让它们的重音字母靠前。

所以,我们如果有 s,ts, t 可以押韵,那么最好在最近公共祖先 LCA,不行再向上 DFS,于是,我们有了思路:对于一个点

  1. 定义 rem\mathrm{rem} 表示该节点的可合并字串数量,遍历所有子节点,计算 rem\mathrm{rem} 为所有子节点 rem′\mathrm{rem'} 之和。

  2. 若本节点为某存储的字符串的起点,则 res\mathrm{res} 加上 11。

  3. 若 rem≥2\mathrm{rem} \geq 2,则令 rem\mathrm{rem} 减去 22,答案 ans\mathrm{ans} 加上 22。(统计个数,不是对数)

  4. 返回 rem\mathrm{rem} 的值,供后累加。

例如:节点 22:

  1. rem=rem5+rem6=1+1=2\mathrm{rem} = \mathrm{rem}_5 + \mathrm{rem}_6 = 1 + 1 = 2。

  2. 节点 22 本身不是起点,rem\mathrm{rem} 不变。

  3. rem≥2\mathrm{rem} \geq 2 成立,rem\mathrm{rem} 变为 00,ans\mathrm{ans} 加 22。

  4. 返回 rem\mathrm{rem},供节点 11 累加。

insert 函数

通普通 Trie 树,但需要注意 ss 倒序遍历。

主函数

  1. 输入 n,Win,W_i。

  2. 对每个 WiW_i,加入 Trie 树。

  3. 循环遍历 00 节点的所有子节点,以其为起点 DFS。

  4. 得到答案,输出 ans\mathrm{ans}。

代码

C++
#include <bits/stdc++.h>
using namespace std;

bool ed[50010]; // 表示点 x 是否是起点
int trie[50010][30]; // 存储点 x 的所有子节点编号
int ans, tot;

void ist(const string &s) { // 插入函数
    int p = 0;
    for(int i = s.size() - 1; i >= 0; i--) {
        int x = s[i] - 'A';
        if(trie[p][x]) p = trie[p][x];
        else p = trie[p][x] = ++tot;
    }
    ed[p] = 1;
    return;
}

int dfs(int x) {
    int rem = 0;
    for(int i = 0; i < 26; i++) { // 0 ~ 25 表示 A ~ Z
        if(!trie[x][i]) continue;
        rem += dfs(trie[x][i]);
    }
    if(ed[x]) rem++;
    if(rem >= 2) rem -= 2, ans += 2;
    return rem;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    int t; cin >> t;
    for(int i = 1; i <= t; i++) {
        cout << "Case #" << i << ": ";
        memset(trie, 0, sizeof(trie));
        memset(ed,   0, sizeof(ed  ));
        tot = 0, ans = 0;
        int n; cin >> n;
        while(n--) {
            string s; cin >> s;
            ist(s);
        }
        for(int i = 0; i < 26; i++) {
            if(!trie[0][i]) continue;
            dfs(trie[0][i]);
        }
        cout << ans << endl;
    }
    return 0;
}
原文