Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đếm mảng con có số lượng 0 và 1 bằng nhau trong C++


Cho mảng arr[] chỉ chứa 0 và 1. Đếm mảng con có số lượng 0 và 1 bằng nhau. Ví dụ [1,0,0] → chỉ [1,0].

Ví dụ

Đầu vào: arr[] = {0, 0, 1, 1, 1, 0}
Đầu ra: 4
Giải thích: [0,0,1,1], [0,1], [1,0], [0,0,1,1,1,0].

Đầu vào: arr[] = {0, 1, 1, 1, 1}
Đầu ra: 1 ([0,1]).

Giải thuật (Vét cạn)

Duyệt 2 vòng lặp tạo mọi mảng con arr[i..j]. Đếm total_0 và total_1. Nếu bằng nhau thì tăng count.

Ví dụ triển khai

#include <bits/stdc++.h>
using namespace std;

int sub_zeroes_ones(int arr[], int size) {
    int count = 0;
    for (int i = 0; i <= size - 1; i++) {
        int total_0 = 0, total_1 = 0;
        for (int j = i; j <= size - 1; j++) {
            if (arr[j] == 0) total_0++;
            else if (arr[j] == 1) total_1++;
            if (total_0 == total_1) count++;
        }
    }
    return count;
}

int main() {
    int arr[] = {0, 1, 1, 0, 0};
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Count of subarrays with equal number of 1's and 0's are: " << sub_zeroes_ones(arr, size);
    return 0;
}

Kết quả

Count of subarrays with equal number of 1's and 0's are: 4