日期:2026年11月16日
ZeroJudge 題目連結:e907.108 p9. 二進位制密碼驗證
解題想法
每組測資為一列字串 $s$,長度 $1 \leq n \leq 30$。檢查這個字串是否符合以下 5 項規則:
- 只有 0、1
- 長度為 8 至 12
- 至少有 2 個 0
- 至少有 3 個 1
- 包含連續的 3 個數字 101
這題用字串格式儲存測資比較方便,用 C 語言的字元陣列很麻煩。讀取字串 $s$ 之後,依序讀取每個字元 $c$,計算其中 0、1 與其它字元的數量。依序檢查是否違反規則 1 到 5,將違反的規則編號加入答案之中。程式碼不難寫,但是檢查項目比較多,寫起來有點長。
Python 程式碼
使用時間約為 14 ms,記憶體約為 9.5 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
s = data[ptr]
ptr += 1
illegal = [] # 違反的規則編號
zero, one, other = 0, 0, 0 # 0、1、其它數字的數量
for c in s:
if c == '0': zero += 1
elif c == '1': one += 1
else: other += 1
# 檢查規則 1
if other > 0: illegal.append(1)
# 檢查規則 2
n = zero + one + other # 長度
if n < 8 or n > 12: illegal.append(2)
# 檢查規則 3
if zero < 2: illegal.append(3)
# 檢查規則 4
if one < 3: illegal.append(4)
# 檢查規則 5
five = False
for i in range(n-2):
if s[i : i+3] == '101':
five = True
break
if not five: illegal.append(5)
# 如果符合所有的規則
if not illegal: illegal.append(0)
result.append(" ".join(map(str, illegal)) + "\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 1 ms,記憶體約為 3.6 MB,通過測試。
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s;
while(cin >> s) {
vector<int> illegal; // 違反的規則編號
int zero = 0, one = 0, other = 0; // 0、1、其它數字的數量
for(char c : s) {
if (c == '0') zero++;
else if (c == '1') one++;
else other++;
}
// 檢查規則 1
if (other > 0) illegal.push_back(1);
// 檢查規則 2
int n = zero + one + other; // 長度
if (n < 8 || n > 12) illegal.push_back(2);
// 檢查規則 3
if (zero < 2) illegal.push_back(3);
// 檢查規則 4
if (one < 3) illegal.push_back(4);
// 檢查規則 5
bool five = false;
for(int i = 0; i < n-2; i++) {
if (s.substr(i, 3) == "101") {
five = true;
break;
}
}
if (!five) illegal.push_back(5);
// 組合答案
if (illegal.empty()) {
cout << "0\n";
} else {
int m = (int)illegal.size();
for(int i = 0; i < m; i++) {
cout << illegal[i] << " \n"[i == m-1];
}
}
}
return 0;
}
使用時間約為 1 ms,記憶體約為 3.6 MB,通過測試。
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s;
while(cin >> s) {
bool illegal[6] = {false}; // 是否違反規則 1 ~ 5
int zero = 0, one = 0, other = 0; // 0、1、其它數字的數量
for(char c : s) {
if (c == '0') zero++;
else if (c == '1') one++;
else other++;
}
// 檢查規則 1
if (other > 0)illegal[1] = true;
// 檢查規則 2
int n = zero + one + other; // 長度
if (n < 8 || n > 12)illegal[2] = true;
// 檢查規則 3
if (zero < 2) illegal[3] = true;
// 檢查規則 4
if (one < 3) illegal[4] = true;
// 檢查規則 5
bool five = false;
for(int i = 0; i < n-2; i++) {
if (s[i] == '1' && s[i+1] == '0' && s[i+2] == '1') {
five = true;
break;
}
}
if (!five) illegal[5] = true;
// 組合答案
string ans;
for(int i = 1; i <= 5; i++) {
if (illegal[i]) {
ans += to_string(i) + " ";
}
}
if (ans.empty()) ans = "0";
else ans.pop_back();
cout << ans << "\n";
}
return 0;
}
沒有留言:
張貼留言