📌  相关文章
📜  对Q查询将所有出现的X替换为Y后的数组总和

📅  最后修改于: 2021-04-22 06:37:10             🧑  作者: Mango

给定一个整数数组arr []Q个查询,任务是为以下类型的每个查询找到数组的总和:

  • 每个查询包含2个整数XY ,其中所有在arr []中出现的X都将由Y代替。
  • 在每个查询之后,打印数组的总和。

例子:

天真的方法:
解决上述问题的最简单方法是遍历数组,并为每个查询将所有X实例替换为Y并计算总和。

时间复杂度: O(N * Q)

高效方法:
要优化上述方法,请执行以下步骤:

  • 预计算数组的总和并将其存储在变量S中,并将数组元素的频率存储在Map计数中
  • 然后,对每个查询执行以下操作:
    • 找到存储在地图中的X的频率。
    • S减去X * count [X]
    • 设置count [Y] = count [X] ,然后设置count [X] = 0
    • Y * count [Y]添加到S。
    • 打印S的更新值。

下面是上述方法的实现:

C++
// C++ implementation to find the sum
// of the array for the given Q queries
 
#include 
using namespace std;
 
// Function that print the sum of
// the array for Q queries
void sumOfTheArrayForQuery(int* A, int N,
                           int* X, int* Y,
                           int Q)
{
    int sum = 0;
 
    // Stores the frequencies
    // of array elements
    unordered_map count;
 
    // Calculate the sum of
    // the initial array and
    // store the frequency of
    // each element in map
 
    for (int i = 0; i < N; i++) {
        sum += A[i];
        count[A[i]]++;
    }
 
    // Iterate for all the queries
 
    for (int i = 0; i < Q; i++) {
        // Store query values
        int x = X[i], y = Y[i];
 
        // Decrement the sum accordingly
        sum -= count[X[i]] * X[i];
 
        // Increment the sum accordingly
        sum += count[X[i]] * Y[i];
 
        // Set count of Y[i]
        count[Y[i]] += count[X[i]];
 
        // Reset count of X[i]
        count[X[i]] = 0;
 
        // Print the sum
        cout << sum << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 1, 3, 2 };
    int X[] = { 2, 3, 5 };
    int Y[] = { 3, 1, 2 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int Q = sizeof(X) / sizeof(X[0]);
 
    // Function call
    sumOfTheArrayForQuery(arr, N, X, Y, Q);
 
    return 0;
}


Java
// Java implementation to
// find the sum of the array
// for the given Q queries
import java.util.*;
class GFG{
   
// Function that print the sum of
// the array for Q queries
public static void sumOfTheArrayForQuery(int[] A, int N,
                                         int[] X, int[] Y,
                                         int Q)
{
  int sum = 0;
 
  // Stores the frequencies
  // of array elements
  // Create an empty hash map
  HashMap count = new HashMap<>();
 
  // Calculate the sum of
  // the initial array and
  // store the frequency of
  // each element in map
  for (int i = 0; i < N; i++)
  {
    sum += A[i];
    if (count.containsKey(A[i]))
    {
      count.replace(A[i],
      count.get(A[i]) + 1);
    }
    else
    {
      count.put(A[i], 1);
    }
  }
 
  // Iterate for all the queries
  for (int i = 0; i < Q; i++)
  {
    // Store query values
    int x = X[i], y = Y[i];
 
    if(count.containsKey(X[i]))
    {
      // Decrement the sum accordingly
      sum -= count.get(X[i]) * X[i];
      // Increment the sum accordingly
      sum += count.get(X[i]) * Y[i];
    }
 
    // Set count of Y[i]
    if(count.containsKey(Y[i]) &&
       count.containsKey(X[i]))
    {
      count.replace(Y[i],
      count.get(Y[i]) +
      count.get(X[i]));
    }
 
    // Reset count of X[i]
    if(count.containsKey(X[i]))
    {
      count.replace(X[i], 0);
    }
 
    // Print the sum
    System.out.print(sum + " ");
  }
}
 
// Driver code
public static void main(String[] args)
{
  int arr[] = {1, 2, 1, 3, 2};
  int X[] = {2, 3, 5};
  int Y[] = {3, 1, 2};
 
  int N = arr.length;
  int Q = X.length;
 
  // Function call
  sumOfTheArrayForQuery(arr, N,
                        X, Y, Q);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 implementation to find the sum
# of the array for the given Q queries
 
# Function that print the sum of
# the array for Q queries
def sumOfTheArrayForQuery(A, N, X, Y, Q):
     
    sum = 0
 
    # Stores the frequencies
    # of array elements
    count = {}
 
    # Calculate the sum of
    # the initial array and
    # store the frequency of
    # each element in map
    for i in range(N):
        sum += A[i]
         
        if A[i] in count:
            count[A[i]] += 1
        else:
            count[A[i]] = 1
 
    # Iterate for all the queries
    for i in range(Q):
 
        # Store query values
        x = X[i]
        y = Y[i]
         
        if X[i] not in count:
            count[X[i]] = 0
        if Y[i] not in count:
            count[Y[i]] = 0
 
        # Decrement the sum accordingly
        sum -= (count[X[i]] * X[i])
 
        # Increment the sum accordingly
        sum += count[X[i]] * Y[i]
 
        # Set count of Y[i]
        count[Y[i]] += count[X[i]]
 
        # Reset count of X[i]
        count[X[i]] = 0
 
        # Print the sum
        print(sum, end = " ")
 
# Driver Code
arr = [ 1, 2, 1, 3, 2, ]
X = [ 2, 3, 5 ]
Y = [ 3, 1, 2 ]
N = len(arr)
Q = len(X)
 
# Function call
sumOfTheArrayForQuery(arr, N, X, Y, Q)
 
# This code is contributed by avanitrachhadiya2155


C#
// C# implementation to
// find the sum of the array
// for the given Q queries
using System;
using System.Collections.Generic;
class GFG{
   
// Function that print the sum of
// the array for Q queries
public static void sumOfTheArrayForQuery(int[] A, int N,
                                         int[] X, int[] Y,
                                         int Q)
{
  int sum = 0;
 
  // Stores the frequencies
  // of array elements
  // Create an empty hash map
  Dictionary count = new Dictionary();
 
  // Calculate the sum of
  // the initial array and
  // store the frequency of
  // each element in map
  for (int i = 0; i < N; i++)
  {
    sum += A[i];
    if (count.ContainsKey(A[i]))
    {
      count[A[i]]= count[A[i]] + 1;
    }
    else
    {
      count.Add(A[i], 1);
    }
  }
 
  // Iterate for all the queries
  for (int i = 0; i < Q; i++)
  {
    // Store query values
    int x = X[i], y = Y[i];
 
    if(count.ContainsKey(X[i]))
    {
      // Decrement the sum accordingly
      sum -= count[X[i]] * X[i];
      // Increment the sum accordingly
      sum += count[X[i]] * Y[i];
    }
 
    // Set count of Y[i]
    if(count.ContainsKey(Y[i]) &&
       count.ContainsKey(X[i]))
    {
      count[Y[i]] = count[Y[i]] +
                    count[X[i]];
    }
 
    // Reset count of X[i]
    if(count.ContainsKey(X[i]))
    {
      count[X[i]] = 0;
    }
 
    // Print the sum
    Console.Write(sum + " ");
  }
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {1, 2, 1, 3, 2};
  int []X = {2, 3, 5};
  int []Y = {3, 1, 2};
 
  int N = arr.Length;
  int Q = X.Length;
 
  // Function call
  sumOfTheArrayForQuery(arr, N,
                        X, Y, Q);
}
}
 
// This code is contributed by Amit Katiyar


输出:
11 5 5






时间复杂度: O(N),因为每个查询的计算复杂度为O(1)。
辅助空间: O(N)