Cho mảng arr[] và hai số A, B. Đếm mảng con có số lần xuất hiện của A và B bằng nhau. Lưu ý: mảng con không chứa A và B (0 lần) cũng được tính.
Ví dụ
Đầu vào: arr[] = {2, 2, 1, 1, 1, 5}, A=1, B=5
Đầu ra: 4 ([2], [2], [2,2], [1,5]).
Đầu vào: arr[] = {5,3,7,5,3}, A=1, B=2
Đầu ra: 15 (tất cả mảng con đều có 0 lần xuất hiện 1 và 2).
Giải thuật (Vét cạn)
Duyệt 2 vòng lặp tạo mảng con arr[i..j]. Đếm total_A, total_B. Nếu bằng nhau thì tăng count.
Ví dụ triển khai
#include <bits/stdc++.h>
using namespace std;
int sub_EqualOccurrence(int arr[], int size, int A, int B) {
int count = 0;
for (int i = 0; i <= size - 1; i++) {
int total_A = 0, total_B = 0;
for (int j = i; j <= size - 1; j++) {
if (arr[j] == A) total_A++;
else if (arr[j] == B) total_B++;
if (total_A == total_B) count++;
}
}
return count;
}
int main() {
int arr[] = {2, 3, 1, 1, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int A = 1, B = 5;
cout << "Count of subarrays with equal number of occurrences of two given elements are: " << sub_EqualOccurrence(arr, size, A, B);
return 0;
}
Kết quả
Count of subarrays with equal number of occurrences of two given elements are: 5