C - Multiple of 7 解説 by evima
Let \(a_i\) be the value of the \(i\)-th through \(|s|\)-th characters seen as a number. For convenience, let \(a_{|s|+1}=0\).
A pair of integers \((l,r)\) satisfies the condition if and only if \((a_l-a_{r+1})/10^{|s|-r}\) is divisible by \(7\). Here, \(10^{|s|-r}\) is coprime with \(7\), so the above is equivalent to \(a_l-a_{r+1}\) being divisible by \(7\).
Let \(b_i\) be the remainder when \(a_i\) is divided by \(7\). Additionally, for each \(0 \leq v < 7\), let \(c_v\) the number of \(i\)’s such that \(b_i=v\).
There are \(N\) pairs of integers \((l, r)\) satisfying the condition if and only if there are \(N\) pairs \((l, r)\) such that \(b_l=b_{r+1}\), which can be further rephrased into \(\sum_{0 \leq v < 7} c_v(c_v-1)/2=N\).
Let us first try to find \(c_v\)’s that satisfy the above. We can do this greedily. Specifically, we should decide \(c_0,c_1,\cdots,c_6\) in this order, and when choosing \(c_k\), we should choose the maximum \(c_k\) that satisfies \(\sum_{0 \leq v \leq k} c_v(c_v-1)/2 \leq N\).
This greedy strategy finds desirable \(c_v\)’s for all \(N\) under the Constraints of this problem. (It does not work for a general \(N\), but we can make it work using the Fermat polygonal number theorem.)
After finding \(c_v\)’s, let us decide \(b_i\) based on them.
When \(b_{i+1}\) is already decided, we can freely choose the value of \(b_i\) by properly setting the \(i\)-th character of \(s\) to 1
, 2
, \(\cdots\), or 7
, so the whole construction can be done backward.
投稿日時:
最終更新: