Immediate Decodability
多组 01 串建 Trie 判前缀,遇 9 结算
正文
// 原题:https://oj.yecheng.tv/p/T1474
// 题意:多组 01 串(每组以单独的 9 结束),判断该组中是否存在一个串是另一个串的前缀,逐组输出结果。
// 思路:对每组数据建 Trie,插入途中命中已有单词结尾(当前串被前缀命中),或插完发现当前结点已有儿子(当前串是别人的前缀),都说明不合法。
// 复杂度:O(所有串总长度) 时间 / O(所有串总长度) 空间
// 易错点:读到 9 时才结算并输出该组,不能在读不到输入后再补输出最后一组。
// 易错点:判定前缀要看「当前结点已有儿子」这个标记,该标记必须在建子结点时顺手打到父结点上。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int ch[2];
bool ed;
bool has;
Node(){
ch[0] = ch[1] = 0;
ed = false;
has = false;
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<Node> tr;
tr.push_back(Node());
bool bad = false;
int t = 1;
string s;
while(cin >> s){
if(s == "9"){
cout << "Set " << t << " is " << (bad ? "not " : "") << "immediately decodable\n";
t++;
tr.clear();
tr.push_back(Node());
bad = false;
continue;
}
int u = 0;
for(int i = 0; i < (int)s.size(); i++){
int c = s[i] - '0';
if(!tr[u].ch[c]){
tr[u].ch[c] = (int)tr.size();
tr[u].has = true;
tr.push_back(Node());
}
u = tr[u].ch[c];
if(tr[u].ed) bad = true;
}
if(tr[u].has) bad = true;
tr[u].ed = true;
}
return 0;
}
一本通·提高篇的其它内容
- 活动安排
- 种树
- 喷水装置
- 加工生产调度
- 智力大冲浪
- 数列极差
- 数列分段
- 线段
- 家庭作业
- 钓鱼
- 糖果传递
- 愤怒的牛
- Best Cow Fences
- 曲线
- 数列分段 II
- 扩散
- 灯泡
- 传送带
- 数的划分
- 生日蛋糕
- 小木棍
- Addition Chains
- 埃及分数
- 平板涂色
- 质数方阵
- 靶形数独
- 电路维修
- 魔板
- Knight Moves
- 棋盘游戏
- Keyboarding
- 移动玩具
- 山峰和山谷
- Oulipo
- 图书管理
- Power Strings
- Seekthe Name, Seek the Fame
- Friends
- A Horrible Poem
- Beads
- Antisymmetry
- 门票
- 收集雪花
- 剪花布条
- Power Strings
- Radio Transmission
- OKR-Periods of Words
- 似乎在梦中见过的样子
- Censoring
- Phone List
- The XOR Largest Pair
- Nikitosh 和异或
- L 语言
- Secret Message 秘密信息
- 背单词
- The Xor-longest Path
- Keywords Search
- 玄武密码
- Censoring
- 单词