ในปัญหานี้ เราได้รับอาร์เรย์ arr[] ขององค์ประกอบ N งานของเราคือสร้างโปรแกรมเพื่อค้นหาผลรวมการเพิ่มลำดับสูงสุดโดยใช้ต้นไม้ดัชนีไบนารีใน C ++
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
arr[] = {4, 1, 9, 2, 3, 7} ผลลัพธ์
13
คำอธิบาย
ลำดับที่เพิ่มสูงสุดคือ 1, 2, 3, 7 ผลรวม =13
แนวทางการแก้ปัญหา
ในการแก้ปัญหา เราจะใช้ Binary Indexed Tree ซึ่งเราจะแทรกค่าและแมปกับ Binary Indexed Tree แล้วหาค่าสูงสุด
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#include <bits/stdc++.h>
using namespace std;
int calcMaxSum(int BITree[], int index){
int maxSum = 0;
while (index > 0){
maxSum = max(maxSum, BITree[index]);
index -= index & (-index);
}
return maxSum;
}
void updateBIT(int BITree[], int newIndex, int index, int val){
while (index <= newIndex){
BITree[index] = max(val, BITree[index]);
index += index & (-index);
}
}
int maxSumIS(int arr[], int n){
int index = 0, maxSum;
map<int, int> arrMap;
for (int i = 0; i < n; i++){
arrMap[arr[i]] = 0;
}
for (map<int, int>::iterator it = arrMap.begin(); it != arrMap.end(); it++){
index++;
arrMap[it->first] = index;
}
int* BITree = new int[index + 1];
for (int i = 0; i <= index; i++){
BITree[i] = 0;
}
for (int i = 0; i < n; i++){
maxSum = calcMaxSum(BITree, arrMap[arr[i]] - 1);
updateBIT(BITree, index, arrMap[arr[i]], maxSum + arr[i]);
}
return calcMaxSum(BITree, index);
}
int main() {
int arr[] = {4, 6, 1, 9, 2, 3, 5, 8};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The Maximum sum increasing subsequence using Binary Indexed Tree is "<<maxSumIS(arr, n);
return 0;
} ผลลัพธ์
The Maximum sum increasing subsquence using Binary Indexed Tree is 19