Tuyên bố vấn đề
Cho một mảng “arr”, nhiệm vụ là tìm số phần tử tối thiểu cần loại bỏ để làm cho mảng tốt.
Một dãy a1, a2, a3. . .an được gọi là tốt nếu với mỗi phần tử a [i], tồn tại một phần tử a [j] (i không bằng j) sao cho a [i] + a [j] là lũy thừa của hai.
arr1[] = {1, 1, 7, 1, 5} Trong mảng trên nếu chúng ta xóa phần tử ‘5’ thì mảng trở thành mảng tốt. Sau cặp arr [i] + arr [j] này là lũy thừa của hai -
- arr [0] + arr [1] =(1 + 1) =2 lũy thừa nào của hai
- arr [0] + arr [2] =(1 + 7) =8 là lũy thừa của hai
Thuật toán
1. We have to delete only such a[i] for which there is no a[j] such that a[i] + a[i] is a power of 2. 2. For each value find the number of its occurrences in the array 3. Check that a[i] doesn’t have a pair a[j]
Ví dụ
#include <iostream>
#include <map>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int minDeleteRequred(int *arr, int n){
map<int, int> frequency;
for (int i = 0; i < n; ++i) {
frequency[arr[i]]++;
}
int delCnt = 0;
for (int i = 0; i < n; ++i) {
bool doNotRemove = false;
for (int j = 0; j < 31; ++j) {
int pair = (1 << j) - arr[i];
if (frequency.count(pair) &&
(frequency[pair] > 1 ||
(frequency[pair] == 1 &&
pair != arr[i]))) {
doNotRemove = true;
break;
}
}
if (!doNotRemove) {
++delCnt;
}
}
return delCnt;
}
int main(){
int arr[] = {1, 1, 7, 1, 5};
cout << "Minimum elements to be deleted = " << minDeleteRequred(arr, SIZE(arr)) << endl;
return 0;
} Đầu ra
Khi bạn biên dịch và thực thi chương trình trên. Nó tạo ra kết quả sau -
Minimum elements to be deleted = 1