
求给定范围内数字奇偶性的概率,即是偶数还是奇数。对于每个查询,我们需要打印 p 和 q,例如用 p / q 表示概率。
Input : N = 5, arr[] = { 6, 5, 2, 1, 7 }query 1: 0 2 2query 2: 1 2 5query 3: 0 1 4Output : 03 41 2
在这个问题中,我们将维护两个数组,分别包含奇数和偶数的数量,直到该索引。这简化了我们的问题,现在我们需要打印它们的数量以及该范围内存在的元素的数量。
解决方案的方法
在这个方法中,我们维护两个数组。它们包含直到第i个索引找到的偶数和奇数的数量,并且像前缀和问题一样解决这个问题。
示例
#include using namespace std;void solve(int arr[], int n, int Q,int query[][3]){ int even[n + 1]; // our array for counting the number of evens find till ith index int odd[n + 1]; // our array for counting the number of odds find till ith index even[0] = 0; odd[0] = 0; // as we are doing 1 based indexing so we just set 0th index of both arrays to 0 for (int i = 0; i < n; i++) { if (arr[i] & 1) { // if we found odd number we increment odd odd[i + 1] = odd[i] + 1; even[i + 1] = even[i]; } else { // else we increment even even[i + 1] = even[i] + 1; odd[i + 1] = odd[i]; } } for (int i = 0; i < Q; i++) { // traversing the queries int r = query[i][2]; // right range int l = query[i][1]; // left range int k = query[i][0]; // type of query int q = r - l + 1; // number of elements in the given range int p; if (k) // k is the type of query and we are finding the //number of elements with same parity in the given range p = odd[r] - odd[l - 1]; else p = even[r] - even[l - 1]; if (!p) // if p is zero we simply print 0 cout << "0n"; else if (p == q) // if p == q we print 1 cout << "1n"; else { int g = __gcd(p, q); cout << p / g << " " << q / g << "n"; // as p and shouldn't have a common gcd so we divide the gcd } }}int main(){ int arr[] = { 6, 5, 2, 1, 7 }; // given array int n = sizeof(arr) / sizeof(int); // size of our array int Q = 2; // number of our queries int query[Q][3] = {{ 0, 2, 2 },{ 1, 2, 5 }}; // given queries solve(arr, n, Q, query); return 0;}
输出
03 4
以上代码的解释
在上述方法中,我们通过维护两个数组来计算找到的到第i个索引的偶数和奇数的数量。现在我们需要找到给定范围内的偶数或奇数的数量,并打印该数量,并打印出现的元素的总数。
立即学习“C++免费学习笔记(深入)”;
结论
在本教程中,我们解决了关于给定范围内偶数或奇数的概率的问题。我们还学习了此问题的C++程序和我们解决此问题的完整方法(正常方法)。我们可以用其他语言(如C、Java、Python和其他语言)编写相同的程序。希望您觉得本教程有帮助。
以上就是C++ 查询给定范围内偶数或奇数的概率的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445105.html
微信扫一扫
支付宝扫一扫