📌  相关文章
📜  用于计算从索引 X 开始的每个第 Y 个索引处存在的数组元素总和的查询

📅  最后修改于: 2021-10-26 05:59:19             🧑  作者: Mango

给定一个大小为N的数组arr[]和一个数组Q[][] ,其中每一行代表一个{ X, Y }形式的查询,每个查询的任务是找到索引X处存在的数组元素的总和, X + Y , X + 2 * Y + …

例子:

朴素的方法:解决这个问题的最简单的方法是遍历每个查询的数组并打印arr[x] + arr[x + y] + arr[x + 2 * y] + …

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
void querySum(int arr[], int N,
              int Q[][2], int M)
{
 
    // Iterate over each query
    for (int i = 0; i < M; i++) {
 
        int x = Q[i][0];
        int y = Q[i][1];
 
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array and calculate
        // the sum of the expression
        while (x < N) {
 
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
 
        cout << sum << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][2] = { { 2, 1 }, { 3, 2 } };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int M = sizeof(Q) / sizeof(Q[0]);
 
    querySum(arr, N, Q, M);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
static void querySum(int arr[], int N,
                     int Q[][], int M)
{
     
    // Iterate over each query
    for(int i = 0; i < M; i++)
    {
        int x = Q[i][0];
        int y = Q[i][1];
         
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array and calculate
        // the sum of the expression
        while (x < N)
        {
             
            // Update sum
            sum += arr[x];
             
            // Update x
            x += y;
        }
        System.out.print(sum + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][] = { { 2, 1 }, { 3, 2 } };
 
    int N = arr.length;
    int M = Q.length;
 
    querySum(arr, N, Q, M);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to Find the sum of
# arr[x]+arr[x+y]+arr[x+2*y] + ...
# for all queries
def querySum(arr, N, Q, M):
 
    # Iterate over each query
    for i in range(M):
        x = Q[i][0]
        y = Q[i][1]
 
        # Stores the sum of
        # arr[x]+arr[x+y]+arr[x+2*y] + ...
        sum = 0
 
        # Traverse the array and calculate
        # the sum of the expression
        while (x < N):
 
            # Update sum
            sum += arr[x]
 
            # Update x
            x += y
        print(sum, end=" ")
 
# Driver Code
if __name__ == '__main__':
    arr = [ 1, 2, 7, 5, 4 ];
    Q = [ [ 2, 1 ], [3, 2 ] ]
    N = len(arr)
    M = len(Q)
    querySum(arr, N, Q, M)
 
    # This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG
{
 
  // Function to Find the sum of
  // arr[x]+arr[x+y]+arr[x+2*y] + ...
  // for all queries
  static void querySum(int []arr, int N,
                       int [,]Q, int M)
  {
 
    // Iterate over each query
    for(int i = 0; i < M; i++)
    {
      int x = Q[i, 0];
      int y = Q[i, 1];
 
      // Stores the sum of
      // arr[x]+arr[x+y]+arr[x+2*y] + ...
      int sum = 0;
 
      // Traverse the array and calculate
      // the sum of the expression
      while (x < N)
      {
 
        // Update sum
        sum += arr[x];
 
        // Update x
        x += y;
      }
      Console.Write(sum + " ");
    }
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = { 1, 2, 7, 5, 4 };
    int [,]Q = { { 2, 1 }, { 3, 2 } };
    int N = arr.Length;
    int M = Q.GetLength(0);
    querySum(arr, N, Q, M);
  }
}
 
// This code is contributed by shikhasingrajput


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
const int sz = 20;
const int sqr = int(sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to sqrt(N).
void precomputeExpressionForAllVal(int arr[], int N,
                                   int dp[sz][sqr])
{
 
    // Iterate over all possible values of X
    for (int i = N - 1; i >= 0; i--) {
 
        // Precompute for all possible values
        // of an expression such that y <= sqrt(N)
        for (int j = 1; j <= sqrt(N); j++) {
 
            // If i + j less than N
            if (i + j < N) {
 
                // Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j];
            }
            else {
 
                // Update dp[i][j]
                dp[i][j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
int querySum(int arr[], int N,
             int Q[][2], int M)
{
 
    // dp[x][y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int dp[sz][sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
    // Traverse the query array, Q[][]
    for (int i = 0; i < M; i++) {
 
        int x = Q[i][0];
        int y = Q[i][1];
 
        // If y is less than or equal
        // to sqrt(N)
        if (y <= sqrt(N)) {
            cout << dp[x][y] << " ";
            continue;
        }
 
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, arr[]
        while (x < N) {
 
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
 
        cout << sum << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][2] = { { 2, 1 }, { 3, 2 } };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int M = sizeof(Q) / sizeof(Q[0]);
 
    querySum(arr, N, Q, M);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int sz = 20;
static int sqr = (int)(Math.sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to Math.sqrt(N).
static void precomputeExpressionForAllVal(int arr[],
                                          int N,
                                          int dp[][])
{
     
    // Iterate over all possible values of X
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Precompute for all possible values
        // of an expression such that y <= Math.sqrt(N)
        for(int j = 1; j <= Math.sqrt(N); j++)
        {
             
            // If i + j less than N
            if (i + j < N)
            {
                 
                // Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j];
            }
            else
            {
                 
                // Update dp[i][j]
                dp[i][j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
static void querySum(int arr[], int N,
                     int Q[][], int M)
{
     
    // dp[x][y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int [][]dp = new int[sz][sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
     
    // Traverse the query array, Q[][]
    for(int i = 0; i < M; i++)
    {
        int x = Q[i][0];
        int y = Q[i][1];
 
        // If y is less than or equal
        // to Math.sqrt(N)
        if (y <= Math.sqrt(N))
        {
            System.out.print(dp[x][y] + " ");
            continue;
        }
         
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, arr[]
        while (x < N)
        {
             
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
        System.out.print(sum + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][] = { { 2, 1 }, { 3, 2 } };
 
    int N = arr.length;
    int M = Q.length;
 
    querySum(arr, N, Q, M);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# python program for the above approach
import math
sz = 20
sqr = int(math.sqrt(sz)) + 1
 
# Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
# for all possible values of X and Y, where Y is
# less than or equal to sqrt(N).
def precomputeExpressionForAllVal(arr, N, dp):
 
    # Iterate over all possible values of X
    for i in range(N - 1, -1, -1) :
       
        # Precompute for all possible values
        #  of an expression such that y <= sqrt(N)
        for j in range (1,int(math.sqrt(N)) + 1):
           
            # If i + j less than N
            if (i + j < N):
                 
                # Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j]
            else:
                 
                # Update dp[i][j]
                dp[i][j] = arr[i]
 
# Function to Find the sum of
# arr[x]+arr[x+y]+arr[x+2*y] + ...
# for all queries
def querySum(arr, N, Q,  M):
   
    # dp[x][y]: Stores sum of
    # arr[x]+arr[x+y]+arr[x+2*y] + ...
    dp = [ [0 for x in range(sz)]for x in range(sqr)]
    precomputeExpressionForAllVal(arr, N, dp)
     
    # Traverse the query array, Q[][]
    for i in range (0,M):
        x = Q[i][0]
        y = Q[i][1]
         
        # If y is less than or equal
        #  to sqrt(N)
        if (y <= math.sqrt(N)):
            print(dp[x][y])
            continue
             
        # Stores the sum of
        # arr[x]+arr[x+y]+arr[x+2*y] + ...
        sum = 0
         
        # Traverse the array, arr[]
        while (x < N):
           
            # Update sum
            sum += arr[x]
             
            # Update x
            x += y
        print(sum)
 
# Driver Code
arr = [ 1, 2, 7, 5, 4 ]
Q = [ [ 2, 1 ], [ 3, 2]]
 
N = len(arr)
 
M = len(Q[0])
querySum(arr, N, Q, M)
 
# This code is contributed by amreshkumar3.


C#
// C# program for the above approach
using System;
 
class GFG{
     
static int sz = 20;
static int sqr = (int)(Math.Sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to Math.Sqrt(N).
static void precomputeExpressionForAllVal(int []arr,
                                          int N,
                                          int [,]dp)
{
     
    // Iterate over all possible values of X
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Precompute for all possible values
        // of an expression such that y <= Math.Sqrt(N)
        for(int j = 1; j <= Math.Sqrt(N); j++)
        {
             
            // If i + j less than N
            if (i + j < N)
            {
                 
                // Update dp[i,j]
                dp[i, j] = arr[i] + dp[i + j, j];
            }
            else
            {
                 
                // Update dp[i,j]
                dp[i, j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
static void querySum(int []arr, int N,
                     int [,]Q, int M)
{
     
    // dp[x,y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int [,]dp = new int[sz, sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
     
    // Traverse the query array, Q[,]
    for(int i = 0; i < M; i++)
    {
        int x = Q[i, 0];
        int y = Q[i, 1];
         
        // If y is less than or equal
        // to Math.Sqrt(N)
        if (y <= Math.Sqrt(N))
        {
            Console.Write(dp[x, y] + " ");
            continue;
        }
         
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, []arr
        while (x < N)
        {
             
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
        Console.Write(sum + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 7, 5, 4 };
    int [,]Q = { { 2, 1 }, { 3, 2 } };
 
    int N = arr.Length;
    int M = Q.GetLength(0);
 
    querySum(arr, N, Q, M);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:
16 5

时间复杂度: O(|Q| * O(N))
辅助空间: O(1)

有效的方法:可以通过使用动态规划技术和平方根分解技术预先计算所有可能的{ X, Y }值的给定表达式的值来解决该问题。以下是递推关系:

请按照以下步骤解决问题:

  • 初始化一个二维数组,比如dp[][] ,以存储XY 的所有可能值的表达式总和,其中Y小于或等于sqrt(N)
  • 使用制表方法填充dp[][]数组。
  • 遍历数组Q[][] 。对于每个查询,检查Q[i][1] 的值是否小于或等于sqrt(N) 。如果发现为真,则打印dp[Q[i][0]][Q[i][1]] 的值
  • 否则,使用上述简单方法计算表达式的值并打印计算值。

下面是我们方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
const int sz = 20;
const int sqr = int(sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to sqrt(N).
void precomputeExpressionForAllVal(int arr[], int N,
                                   int dp[sz][sqr])
{
 
    // Iterate over all possible values of X
    for (int i = N - 1; i >= 0; i--) {
 
        // Precompute for all possible values
        // of an expression such that y <= sqrt(N)
        for (int j = 1; j <= sqrt(N); j++) {
 
            // If i + j less than N
            if (i + j < N) {
 
                // Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j];
            }
            else {
 
                // Update dp[i][j]
                dp[i][j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
int querySum(int arr[], int N,
             int Q[][2], int M)
{
 
    // dp[x][y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int dp[sz][sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
    // Traverse the query array, Q[][]
    for (int i = 0; i < M; i++) {
 
        int x = Q[i][0];
        int y = Q[i][1];
 
        // If y is less than or equal
        // to sqrt(N)
        if (y <= sqrt(N)) {
            cout << dp[x][y] << " ";
            continue;
        }
 
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, arr[]
        while (x < N) {
 
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
 
        cout << sum << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][2] = { { 2, 1 }, { 3, 2 } };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int M = sizeof(Q) / sizeof(Q[0]);
 
    querySum(arr, N, Q, M);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int sz = 20;
static int sqr = (int)(Math.sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to Math.sqrt(N).
static void precomputeExpressionForAllVal(int arr[],
                                          int N,
                                          int dp[][])
{
     
    // Iterate over all possible values of X
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Precompute for all possible values
        // of an expression such that y <= Math.sqrt(N)
        for(int j = 1; j <= Math.sqrt(N); j++)
        {
             
            // If i + j less than N
            if (i + j < N)
            {
                 
                // Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j];
            }
            else
            {
                 
                // Update dp[i][j]
                dp[i][j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
static void querySum(int arr[], int N,
                     int Q[][], int M)
{
     
    // dp[x][y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int [][]dp = new int[sz][sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
     
    // Traverse the query array, Q[][]
    for(int i = 0; i < M; i++)
    {
        int x = Q[i][0];
        int y = Q[i][1];
 
        // If y is less than or equal
        // to Math.sqrt(N)
        if (y <= Math.sqrt(N))
        {
            System.out.print(dp[x][y] + " ");
            continue;
        }
         
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, arr[]
        while (x < N)
        {
             
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
        System.out.print(sum + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 7, 5, 4 };
    int Q[][] = { { 2, 1 }, { 3, 2 } };
 
    int N = arr.length;
    int M = Q.length;
 
    querySum(arr, N, Q, M);
}
}
 
// This code is contributed by shikhasingrajput

蟒蛇3

# python program for the above approach
import math
sz = 20
sqr = int(math.sqrt(sz)) + 1
 
# Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
# for all possible values of X and Y, where Y is
# less than or equal to sqrt(N).
def precomputeExpressionForAllVal(arr, N, dp):
 
    # Iterate over all possible values of X
    for i in range(N - 1, -1, -1) :
       
        # Precompute for all possible values
        #  of an expression such that y <= sqrt(N)
        for j in range (1,int(math.sqrt(N)) + 1):
           
            # If i + j less than N
            if (i + j < N):
                 
                # Update dp[i][j]
                dp[i][j] = arr[i] + dp[i + j][j]
            else:
                 
                # Update dp[i][j]
                dp[i][j] = arr[i]
 
# Function to Find the sum of
# arr[x]+arr[x+y]+arr[x+2*y] + ...
# for all queries
def querySum(arr, N, Q,  M):
   
    # dp[x][y]: Stores sum of
    # arr[x]+arr[x+y]+arr[x+2*y] + ...
    dp = [ [0 for x in range(sz)]for x in range(sqr)]
    precomputeExpressionForAllVal(arr, N, dp)
     
    # Traverse the query array, Q[][]
    for i in range (0,M):
        x = Q[i][0]
        y = Q[i][1]
         
        # If y is less than or equal
        #  to sqrt(N)
        if (y <= math.sqrt(N)):
            print(dp[x][y])
            continue
             
        # Stores the sum of
        # arr[x]+arr[x+y]+arr[x+2*y] + ...
        sum = 0
         
        # Traverse the array, arr[]
        while (x < N):
           
            # Update sum
            sum += arr[x]
             
            # Update x
            x += y
        print(sum)
 
# Driver Code
arr = [ 1, 2, 7, 5, 4 ]
Q = [ [ 2, 1 ], [ 3, 2]]
 
N = len(arr)
 
M = len(Q[0])
querySum(arr, N, Q, M)
 
# This code is contributed by amreshkumar3.

C#

// C# program for the above approach
using System;
 
class GFG{
     
static int sz = 20;
static int sqr = (int)(Math.Sqrt(sz)) + 1;
 
// Function to sum of arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all possible values of X and Y, where Y is
// less than or equal to Math.Sqrt(N).
static void precomputeExpressionForAllVal(int []arr,
                                          int N,
                                          int [,]dp)
{
     
    // Iterate over all possible values of X
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Precompute for all possible values
        // of an expression such that y <= Math.Sqrt(N)
        for(int j = 1; j <= Math.Sqrt(N); j++)
        {
             
            // If i + j less than N
            if (i + j < N)
            {
                 
                // Update dp[i,j]
                dp[i, j] = arr[i] + dp[i + j, j];
            }
            else
            {
                 
                // Update dp[i,j]
                dp[i, j] = arr[i];
            }
        }
    }
}
 
// Function to Find the sum of
// arr[x]+arr[x+y]+arr[x+2*y] + ...
// for all queries
static void querySum(int []arr, int N,
                     int [,]Q, int M)
{
     
    // dp[x,y]: Stores sum of
    // arr[x]+arr[x+y]+arr[x+2*y] + ...
    int [,]dp = new int[sz, sqr];
 
    precomputeExpressionForAllVal(arr, N, dp);
     
    // Traverse the query array, Q[,]
    for(int i = 0; i < M; i++)
    {
        int x = Q[i, 0];
        int y = Q[i, 1];
         
        // If y is less than or equal
        // to Math.Sqrt(N)
        if (y <= Math.Sqrt(N))
        {
            Console.Write(dp[x, y] + " ");
            continue;
        }
         
        // Stores the sum of
        // arr[x]+arr[x+y]+arr[x+2*y] + ...
        int sum = 0;
 
        // Traverse the array, []arr
        while (x < N)
        {
             
            // Update sum
            sum += arr[x];
 
            // Update x
            x += y;
        }
        Console.Write(sum + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 7, 5, 4 };
    int [,]Q = { { 2, 1 }, { 3, 2 } };
 
    int N = arr.Length;
    int M = Q.GetLength(0);
 
    querySum(arr, N, Q, M);
}
}
 
// This code is contributed by shikhasingrajput

Javascript


输出:
16 5

时间复杂度: O(N * sqrt(N) + |Q| * sqrt(N))
辅助空间: O(N * sqrt(N))

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程