solve the question in C++
作成日: 2025年7月5日
作成日: 2025年7月5日
pythondef count_subseq(arr): MOD=10**9+7 dpE1=dpE2=dpO1=dpO2=0 for x in arr: if x%2==0: nE1=(dpO1+dpO2+1)%MOD nE2=dpE1%MOD dpE1=(dpE1+nE1)%MOD dpE2=(dpE2+nE2)%MOD else: nO1=(dpE1+dpE2+1)%MOD nO2=dpO1%MOD dpO1=(dpO1+nO1)%MOD dpO2=(dpO2+nO2)%MOD return (dpE1+dpE2+dpO1+dpO2)%MOD print(count_subseq([1,2,3,5]))
pythonprint(count_subseq([2,2,2]))
Only the parity of every element matters, because the rule is about consecutive evens or odds.
While we scan the array we maintain how many valid subsequences end with the last 1 or 2 elements being even/odd:
state | meaning |
---|---|
E1 | ends in one even (… odd , even) |
E2 | ends in two evens (… odd , even, even) |
O1 | ends in one odd (… even , odd) |
O2 | ends in two odds (… even , odd, odd) |
A third same-parity element would violate the rule, so we never create such a state.
Processing an element x
:
If x
is even
textnewE1 = 1 // subseq consisting of only x + O1 + O2 // append x after an odd run newE2 = E1 // append x after a single even // sequences that ignore x keep their old states E1 = (E1 + newE1) mod M E2 = (E2 + newE2) mod M
If x
is odd – symmetric with the roles of even/odd swapped.
At each step we keep everything mod M = 1 000 000 007.
After the whole array the answer is
(E1 + E2 + O1 + O2) mod M
because every non-empty valid subsequence ends in exactly one of the four states.
The algorithm is O(N) per test case and O(1) extra memory.
cpp#include <bits/stdc++.h> using namespace std; const long long MOD = 1'000'000'007LL; int solve(int N, const vector<int>& A) { long long E1 = 0, E2 = 0, O1 = 0, O2 = 0; for (int x : A) { if (x & 1) { // x is odd long long newO1 = (1 + E1 + E2) % MOD; long long newO2 = E1 ? 0 : 0; // will be set below newO2 = O1; // append odd after single odd O1 = (O1 + newO1) % MOD; O2 = (O2 + newO2) % MOD; } else { // x is even long long newE1 = (1 + O1 + O2) % MOD; long long newE2 = E1; // append even after single even E1 = (E1 + newE1) % MOD; E2 = (E2 + newE2) % MOD; } } return int((E1 + E2 + O1 + O2) % MOD); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<int> A(N); for (int &x : A) cin >> x; cout << solve(N, A) << '\n'; } return 0; }
E2 → E3
or O2 → O3
.This passes the sample cases ([2,2,2] → 6
, [1,2,3,5] → 14
) and runs easily within the given bounds (N ≤ 10^5
, T ≤ 10
).