คำชี้แจงปัญหา
กำหนดอาร์เรย์ของจำนวนเต็ม n จำนวนเต็มและคิวรี q แต่ละเคียวรีมีช่วงตั้งแต่ l ถึง r ค้นหาผลรวมคำนำหน้าสูงสุดสำหรับช่วง l – r.
ตัวอย่าง
If input array is arr[] = {-1, 2, 3, -5} and
queries = 2 and ranges are:
l = 0, r = 3
l = 1, r = 3 then output will be 4 and 5. - ช่วง (0, 3) ในแบบสอบถามที่ 1 มี [-1, 2, 3, -5] เนื่องจากเป็นคำนำหน้า เราจึงต้องเริ่มจาก -1 ดังนั้น ผลรวมคำนำหน้าสูงสุดจะเป็น -1 + 2 + 3 =4
- ช่วง (1, 3) ในแบบสอบถามที่ 2 มี [2, 3, -5] เนื่องจากเป็นคำนำหน้า เราจึงต้องเริ่มจาก 2 ดังนั้น ผลรวมคำนำหน้าสูงสุดจะเป็น 2 + 3 =5
อัลกอริทึม
- สร้างแผนผังกลุ่มโดยที่แต่ละโหนดเก็บค่าสองค่า s (sum และ prefix_sum) และทำการค้นหาช่วงเพื่อค้นหาผลรวมคำนำหน้าสูงสุด
- เพื่อหาผลรวมคำนำหน้าสูงสุด เราจำเป็นต้องมีสองสิ่ง สิ่งแรกคือผลรวมและผลรวมนำหน้าอื่น
- การรวมจะส่งกลับสองสิ่ง ได้แก่ ผลรวมของช่วงและผลรวมนำหน้าที่จะเก็บ max(prefix.left, prefix.sum + prefix.right) ไว้ในแผนผังกลุ่ม
- ผลรวมคำนำหน้าสูงสุดสำหรับการรวมกันสองช่วงจะเป็นผลรวมนำหน้าจากด้านซ้ายหรือผลรวมของด้านซ้าย+ผลรวมนำหน้าด้านขวา แล้วแต่จำนวนใดจะสูงสุด
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
typedef struct node {
int sum;
int prefix;
} node;
node tree[4 * 10000];
void build(int *arr, int idx, int start, int end) {
if (start == end) {
tree[idx].sum = arr[start];
tree[idx].prefix = arr[start];
} else {
int mid = (start + end) / 2;
build(arr, 2 * idx + 1, start, mid);
build(arr, 2 * idx + 2, mid + 1, end);
tree[idx].sum = tree[2 * idx + 1].sum + tree[2 *
idx + 2].sum;
tree[idx].prefix = max(tree[2 * idx + 1].prefix,
tree[2 * idx + 1].sum + tree[2 * idx + 2].prefix);
}
}
node query(int idx, int start, int end, int l, int r) {
node result;
result.sum = result.prefix = -1;
if (start > r || end < l) {
return result;
}
if (start >= l && end <= r) {
return tree[idx];
}
int mid = (start + end) / 2;
if (l > mid) {
return query(2 * idx + 2, mid + 1, end, l, r);
}
if (r <= mid) {
return query(2 * idx + 1, start, mid, l, r);
}
node left = query(2 * idx + 1, start, mid, l, r);
node right = query(2 * idx + 2, mid + 1, end, l, r);
result.sum = left.sum + right.sum;
result.prefix = max(left.prefix, left.sum + right.prefix);
return result;
}
int main() {
int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = sizeof(arr) / sizeof(arr[0]);
build(arr, 0, 0, n - 1);
cout << "Result = " << query(0, 0, n - 1, 3, 5).prefix
<< endl;
return 0;
} ผลลัพธ์
เมื่อคุณคอมไพล์และรันโปรแกรมข้างต้น มันสร้างผลลัพธ์ต่อไปนี้ -
Result = -1