D - バランス食生活 / Balanced Diet 解説 by admin
gpt-5.3-codexOverview
This problem can be rephrased by converting the condition “vegetable total equals fruit total” for each interval into a condition on the prefix sums of their difference.
By counting pairs of positions that share the same cumulative difference, we can efficiently count all valid intervals.
Analysis
For each day:
- V corresponds to \((v_i,f_i)=(1,0)\), so the difference \(v_i-f_i\) is \(+1\)
- F has a difference of \(-1\)
- B, N have a difference of \(0\)
The condition for an interval \([l,r]\) to be a balanced period: [ \sum_{i=l}^r vi = \sum{i=l}^r fi ] is equivalent to: [ \sum{i=l}^r (v_i-f_i)=0 ]
Now, define the prefix (cumulative sum from the beginning) as: [ Dk=\sum{i=1}^k (v_i-f_i),\quad D_0=0 ]
Then the difference sum over the interval \([l,r]\) is: [ Dr-D{l-1} ]
So the balance condition becomes: [ Dr=D{l-1} ]
In other words, we just need to count pairs of positions that share the same cumulative difference value.
Naively checking all intervals \((l,r)\) would require \(O(N^2)\) intervals, which is too slow for \(N\le 10^6\).
Instead, we scan from left to right once, maintaining an associative array that tracks “how many times each difference value has appeared so far.”
- Let
diffbe the current cumulative difference - If at the current point
cnt[diff]occurrences of the same difference have appeared in the past,
all of them form “balanced periods ending at the current position” - So we add
ans += cnt[diff] - Then update
cnt[diff] += 1
This counts all valid intervals without duplication.
Algorithm
- Initialize
diff = 0(cumulative difference) andans = 0. - Maintain
cnt(difference value → occurrence count) as a dictionary, with the initial valuecnt[0]=1.
(This represents the length-0 prefix \(D_0\). Without this, intervals starting from the beginning would be missed.) - Process the string
Sfrom left to right:- If
V, thendiff += 1 - If
F, thendiff -= 1 - If
BorN, no change ans += cnt[diff]cnt[diff] += 1
- If
- Output
ans.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
(The number of distinct difference values is at most \(2N+1\))
Implementation Notes
The initialization
cnt[0] = 1is crucial.Since
BandNdo not change the difference, it suffices to update only forVandFusingif/elif.The answer can be as large as \(N(N+1)/2\) (the total number of intervals), so Python’s
inthandles it safely.Source Code
import sys
from collections import defaultdict
def main():
input = sys.stdin.readline
N = int(input().strip())
S = input().strip()
diff = 0
cnt = defaultdict(int)
cnt[0] = 1
ans = 0
for ch in S:
if ch == 'V':
diff += 1
elif ch == 'F':
diff -= 1
# 'B' and 'N' do not change diff
ans += cnt[diff]
cnt[diff] += 1
print(ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
投稿日時:
最終更新: