1 条题解
-
0
文字教学
这道题用三个前缀和数组分别统计三个品种的数量,实现高效查询:
- 定义
s1[i]、s2[i]、s3[i]分别表示前i头奶牛中品种1、2、3的数量。 - 预处理:遍历每头奶牛,对应品种的前缀和数组在当前位置加1,其余品种继承前一个位置的值。
- 查询区间
[a,b]时,每个品种的数量 = 该品种前缀和在b位置的值 - 在a-1位置的值。
代码
#include <bits/stdc++.h> using namespace std; int s1[100005], s2[100005], s3[100005]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q, x, a, b; cin >> n >> q; for (int i = 1; i <= n; ++i) { cin >> x; s1[i] = s1[i-1]; s2[i] = s2[i-1]; s3[i] = s3[i-1]; if (x == 1) s1[i]++; else if (x == 2) s2[i]++; else s3[i]++; } while (q--) { cin >> a >> b; cout << s1[b]-s1[a-1] << " " << s2[b]-s2[a-1] << " " << s3[b]-s3[a-1] << "\n"; } return 0; } - 定义
- 1
信息
- ID
- 5159
- 时间
- 2000ms
- 内存
- 250MiB
- 难度
- 3
- 标签
- 递交数
- 8
- 已通过
- 6
- 上传者
京公网安备 11011102002149号