题解:P16268 [蓝桥杯 2026 省 Java B 组] 游戏指令解析器
发表于更新于
字数总计:227阅读时长:1分钟 JohnCh's Home
题解洛谷题解:P16268 [蓝桥杯 2026 省 Java B 组] 游戏指令解析器
John Chiao题目
输入 $n$ 个字符串,$m$ 个匹配串,统计每个 $m$ 在 $n$ 中的匹配次数。
思路
由于本题的规模非常小,可以直接暴力匹配,对于每一个 $s$ 遍历一次 $c$ 判断是否为 $s$ 的前缀(substr 用于取子串,substr(0, s.size()) 代表从 0 开始,长度为 s.size() 的子串,也就是开头 $|s|$ 个字符)。
代码
时间复杂度:$O(n\times m\times |s|)$。
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
| #include<bits/stdc++.h> using namespace std; int n, m; string c[105]; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> c[i];
for (int i = 1; i <= m; i++) { string s; cin >> s; int ans = 0, flg; for (int j = 1; j <= n; j++) { if (s == c[j].substr(0, s.size())) { ans++; flg = j; } } if (!ans) cout << "unknown"; else if (ans > 1) cout << "ambiguous"; else cout << c[flg]; cout << endl; } return 0; }
|