1 条题解
-
0
练30.3 奇偶分家
解题思路
读入 N 个数,分别统计奇数与偶数个数,先输出奇再输出偶。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
计数而不是求和。
复杂度
时间 O(n),额外空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; int odd = 0, even = 0; while (n--) { long long x; cin >> x; if (x % 2) odd++; else even++; } cout << odd << " " << even << "\n"; return 0; }
- 1