Home > Backend Development > C++ > Find initial array from given array after range sum query in C++

Find initial array from given array after range sum query in C++

PHPz
Release: 2023-09-17 17:09:02
forward
2735 people have browsed it

在 C++ 中的范围求和查询后从给定数组中查找初始数组

In this problem, we get an array res[] of size N. Our task is to find initial array from given array after range sum query.

We need to find the starting array on which the array rel[] will be returned when executing a [s, e, val] query.

The solution for each [s, e, val] query is

s -> starting index

e -> ending index

val -> Update the value to be added to each element from s to e in the array.

Let us take an example to understand this problem,
Input : rel[] = {7, 4, 8}
Query[][] = {{1, 2, 1},
{0, 1, 3}}
Output : {4, 0, 7}
Copy after login

Explanation The translation of −

is:

Explanation

initialArray = {4, 0, 7}; query = {1, 2, 1}; finalArray = {4, 1, 8}
initialArray = {4, 1, 8}; query = {0, 1, 3}; finalArray = {7, 4, 8}
Copy after login

Solution

The simple way to solve the problem is to iterate through all queries, solve them the same way we solved the problem for all queries, and then return the found array at the end. Here, in order to find the initial array, we need to operate it in the opposite way, i.e. subtract it from the given array.

Example

Program example to illustrate how our solution works

#include <iostream>
using namespace std;
void calcInitialArrayQueries(int arr[], int n, int query[][3], int q) {
   for (int i = 0; i < q; i++) {
      for (int j = query[i][0];j <= query[i][1]; j++) {
         arr[j] = arr[j] - query[i][2];
      }
   }
   for (int i = 0; i < n; i++)
      cout<<arr[i]<<" ";
}
int main() {
   int arr[] = { 5, 1, 8, 2, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   int query[][3] = { {0, 2, -2}, {1, 4, 3}};
   int q = sizeof(query) / sizeof(query[0]);
   cout<<"Initial array : "; calcInitialArrayQueries(arr, n, query, q);
   return 0;
}
Copy after login

Output

Initial array : 7 0 7 -1 6
Copy after login

The above is the detailed content of Find initial array from given array after range sum query in C++. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template