A - 幸運の番号 / Lucky Number 解説 by admin 印刷ページ
gpt-6-astra-mediumOverview
We need to determine whether the string \(S\) contains at least \(K\) occurrences of 7. By decrementing the count of “how many more are needed” each time we find a 7, we can determine whether it is a win.
Analysis
What matters for whether it is a win is only the number of 7s, not their positions. Therefore, a naive approach of checking the string from beginning to end is sufficient. Since \(N \leq 100\), this approach will not result in TLE.
In the presented code, the remaining number of 7s needed is maintained using a variable need.
- Initially, set
need = K. - Each time a
7is found, decrementneedby \(1\).
If \(C\) is the total count of 7s in the entire string, then after scanning, we have
\(\mathrm{need} = K - C\).
Therefore, the winning condition \(C \geq K\) is equivalent to \(\mathrm{need} \leq 0\).
For example, if \(K = 2\) and \(S =\) 7077, each time a 7 is found, need changes as \(2 \to 1 \to 0 \to -1\). At the end, since need <= 0, the answer is Yes.
Note that because the condition is “at least \(K\)”, checking only need == 0 will result in a WA if there are more than \(K\) occurrences of 7.
Algorithm
- Read \(N, K, S\).
- Initialize
needwith \(K\). - Examine each character of \(S\) in order; if it is
7, decrementneedby \(1\). - If
need <= 0, outputYes; otherwise, outputNo.
Complexity
- Time complexity: \(O(N)\)
Each character of the string is examined once. - Space complexity: \(O(N)\)
Required to store the input string \(S\). Excluding the storage of the input, the auxiliary space complexity is \(O(1)\).
Implementation Notes
Read \(S\) as a string rather than an integer. This allows you to handle cases with leading
0s or very long numbers directly.When comparing each character, use the character
'7'instead of the integer7.Since
needcan become negative, use a signed integer type such asint, as in the code.The output is case-sensitive, so print
YesorNoexactly as specified.Source Code
// 問題文から独立に実装: 7 を見つけるごとに残り必要数を減らす
#include <iostream>
#include <string>
int main() {
int n, k; std::string s; std::cin >> n >> k >> s;
int need = k;
for (int i = 0; i < n; ++i) if (s[i] == '7') need--;
std::cout << (need <= 0 ? "Yes" : "No") << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
投稿日時:
最終更新: