ในการหาความน่าจะเป็นของความเท่าเทียมกันของตัวเลข กล่าวคือ เป็นเลขคู่หรือคี่ และสำหรับช่วงที่กำหนด สำหรับแต่ละข้อความค้นหา เราจำเป็นต้องพิมพ์ p และ q ที่แสดงถึงความน่าจะเป็นด้วย p / q เป็นต้น
Input : N = 5, arr[] = { 6, 5, 2, 1, 7 }
query 1: 0 2 2
query 2: 1 2 5
query 3: 0 1 4
Output : 0
3 4
1 2 ในปัญหานี้ เราจะรักษาอาร์เรย์สองอาร์เรย์ที่มีจำนวนเลขคี่และเลขคู่จนถึงดัชนีนั้น สิ่งนี้ทำให้ปัญหาของเราง่ายขึ้น และตอนนี้เราต้องพิมพ์จำนวนและจำนวนองค์ประกอบที่มีอยู่ในช่วงนั้น
แนวทางในการหาแนวทางแก้ไข
ในแนวทางนี้ เราคงไว้สองอาร์เรย์ ประกอบด้วยจำนวนคู่และเลขคี่ที่พบจนถึงดัชนี ith และแก้ปัญหานี้เช่นปัญหาผลรวมนำหน้า
ตัวอย่าง
#include <bits/stdc++.h>
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 << "0\n";
else if (p == q) // if p == q we print 1
cout << "1\n";
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;
} ผลลัพธ์
0 3 4
คำอธิบายของโค้ดด้านบน
ในแนวทางข้างต้น เรานับจำนวนคู่และเลขคี่ที่พบในดัชนี ith โดยรักษาสองอาร์เรย์ ตอนนี้เราจำเป็นต้องค้นหาจำนวนเลขคู่หรือเลขคี่ในช่วงที่กำหนดและพิมพ์ตัวเลขนั้นและพิมพ์จำนวนองค์ประกอบทั้งหมดที่มีอยู่
บทสรุป
ในบทช่วยสอนนี้ เราจะแก้คำถามเกี่ยวกับความน่าจะเป็นของเลขคู่หรือคี่ในช่วงที่กำหนด นอกจากนี้เรายังได้เรียนรู้โปรแกรม C++ สำหรับปัญหานี้และแนวทางที่สมบูรณ์ (ปกติ) ซึ่งเราแก้ไขปัญหานี้ เราสามารถเขียนโปรแกรมเดียวกันในภาษาอื่นๆ เช่น C, java, python และภาษาอื่นๆ เราหวังว่าคุณจะพบว่าบทช่วยสอนนี้มีประโยชน์