Table of Contents
grammar
algorithm
Method 1: Brute force cracking
Example
Output
illustrate
Method 2: Efficient sorting
in conclusion
Home Backend Development C++ Written in C++, translate the following into Chinese: Calculate the minimum common sum of K arrays after deleting part of the array

Written in C++, translate the following into Chinese: Calculate the minimum common sum of K arrays after deleting part of the array

Sep 12, 2023 am 11:41 AM
written in c delete array minimum common sum

Written in C++, translate the following into Chinese: Calculate the minimum common sum of K arrays after deleting part of the array

When using C arrays, we sometimes need to calculate the minimum common sum among multiple arrays while removing part of their suffixes. In this article, we will explore an efficient solution to this problem using C.

grammar

Let's first analyze the syntax of our chosen method before proceeding to implement it in our code -

int findMinimumCommonSum(vector<vector<int>>& arrays, int suffixToRemove);
Copy after login

algorithm

Here is a step-by-step algorithm to solve the problem of finding the least common sum after deleting part of the array suffix -

  • First define the function findMinimumCommonSum, which accepts two parameters - arrays, a two-dimensional vector representing the array, and suffixToRemove, an integer representing the number of elements to be removed from the suffix of each array.

  • Initialize a variable minimumSum to store the minimum common sum, and set its initial value to a larger value.

  • Iterate through each array in the array vector.

  • Determine the size of the current array.

  • To avoid ending up with an empty array, you should consider skipping iterations of suffixToRemove that are greater than or equal to the total size of the current array. Removing all characters in this case does not produce any meaningful output.

  • Calculate the sum of array elements from index 0 to size - suffixToRemove - 1 and store it in the variable currentSum.

  • If currentSum is less than minimumSum, use the value of currentSum to update minimumSum.

  • After traversing all arrays, minimumSum will contain the smallest common sum in the array after removing the specified suffix.

Method 1: Brute force cracking

In this approach we will generate all possible combinations of the suffixes to be removed and calculate the sum for each combination. The smallest sum among all combinations is the least common sum.

Example

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

int findMinimumCommonSum(vector<vector<int>>& arrays, int suffixToRemove) {
   int minimumSum = INT_MAX;
   int k = arrays.size();

   for (int i = 0; i < k; i++) {
      int size = arrays[i].size();

      if (suffixToRemove >= size)
         continue;

      vector<bool> suffix(size, false);
      fill(suffix.begin() + size - suffixToRemove, suffix.end(), true);

      do {
         int currentSum = 0;
         
         for (int j = 0; j < k; j++) {
            int arraySum = 0;
            for (int l = 0; l < size; l++) {
               if (!suffix[l])
                  arraySum += arrays[j][l];
            }
            currentSum += arraySum;
         }

         if (currentSum < minimumSum)
            minimumSum = currentSum;

      } while (next_permutation(suffix.begin(), suffix.end()));
   }

   return minimumSum;
}

int main() {
   vector<vector<int>> arrays = {{1, 2, 3},
                                 {4, 5, 6},
                                 {7, 8, 9}};

   int suffixToRemove = 1;

   int minimumCommonSum = findMinimumCommonSum(arrays, suffixToRemove);

   cout << "Minimum Common Sum: " << minimumCommonSum << endl;

   return 0;
}
Copy after login

Output

Minimum Common Sum: 27
Copy after login

illustrate

In the brute force method, our goal is to find the smallest common sum between multiple arrays after removing a specified number of elements from their suffixes. The method involves generating all possible combinations of the suffixes to be removed and calculating the sum of each combination. The smallest sum among all combinations will be the smallest common sum.

To implement this approach, we define a function called findMinimumCommonSum, which accepts two parameters: an array (a 2D vector representing the array) and suffixToRemove (an integer representing the number of elements to be removed from each array suffix) ).

Inside the function, we initialize a variable minimumSum to store the minimum common sum, and the initial value is set to the maximum possible value of type int. Then we iterate through each array in the array vector. For each array, we determine its size and check if the suffixToRemove value is less than the size.

If the conditions are met, we use a Boolean vector to generate all possible suffix combinations. We fill the last suffixToRemove elements with true and the remaining elements with false. For each array, we determine its size and check if the suffixToRemove value is less than the size.

We proceed by computing the sum of the array values ​​corresponding to the false indicators in the suffix vector, for each combination. We repeat this process for all arrays, updating currentSum accordingly.

Finally, we compare currentSum with minimumSum, and if currentSum is smaller, update minimumSum. After iterating through all arrays and combinations, minimumSum will contain the minimum common sum after removing the specified suffix.

Method 2: Efficient sorting

In this method, we will sort the arrays in non-decreasing order and calculate the sum of the first size - suffixToRemove elements of each array. The smallest sum among all arrays will be the smallest common sum.

Example

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

int findMinimumCommonSum(vector<vector<int>>& arrays, int suffixToRemove) {
   int minimumSum = INT_MAX;
   int k = arrays.size();

   for (int i = 0; i < k; i++) {
      int size = arrays[i].size();

      if (suffixToRemove >= size)
         continue;

      sort(arrays[i].begin(), arrays[i].end());

      int currentSum = 0;
      for (int j = 0; j < size - suffixToRemove; j++)
         currentSum += arrays[i][j];

      if (currentSum < minimumSum)
         minimumSum = currentSum;
   }

   return minimumSum;
}

int main() {
   vector<vector<int>> arrays = {{1, 2, 3},
                                 {4, 5, 6},
                                 {7, 8, 9}};

   int suffixToRemove = 1;

   int minimumCommonSum = findMinimumCommonSum(arrays, suffixToRemove);

   cout << "Minimum Common Sum: " << minimumCommonSum << endl;
   
   return 0;
}
Copy after login

Output

Minimum Common Sum: 3
Copy after login

illustrate

In efficient sorting method, our goal is to find the minimum common sum between multiple arrays after removing a specified number of elements from the suffix. This approach takes advantage of the fact that sorting the array simplifies the calculation of the minimum sum.

To implement this approach, we define a function called findMinimumCommonSum, which accepts two parameters: an array (a 2D vector representing the array) and suffixToRemove (an integer representing the number of elements to be removed from each array suffix) ).

Inside the function, we initialize a variable minimumSum to store the minimum common sum, and the initial value is set to the maximum possible value of type int. Then we iterate through each array in the array vector. For each array, we determine its size and check if the suffixToRemove value is less than the size.

When this prerequisite is met, one of our next steps will be to sort all the individual components in our array in ascending order; this approach mainly helps to ensure that smaller objects are in their initial section to improve the sorting and readability.

Next, we calculate the sum of the first size - suffixToRemove elements in the sorted array. This corresponds to removing the specified number of elements from the suffix. We update currentSum accordingly.

Finally, we compare currentSum with minimumSum, and if currentSum is smaller, update minimumSum. After iterating through all arrays, minimumSum will contain the minimum common sum after removing the specified suffix.

This method is very efficient because it does not require generating and iterating all possible combinations like brute force methods. Instead, it exploits the ordering properties to simplify the calculation of the minimum sum, thus improving performance.

in conclusion

In this article, we explore an efficient way to find the smallest common sum among K arrays in C, after removing part of their suffixes. We discussed two methods - brute force and efficient sorting. The brute force method involves generating all combinations of suffixes, while the efficient sort method sorts the array and calculates the sum of the first few elements. Depending on the size of the array and the number of suffix elements to be removed, efficient sort is usually more efficient. By implementing these methods in a C program, you can easily find the smallest common sum from multiple arrays and handle the removal of suffixes efficiently.

The above is the detailed content of Written in C++, translate the following into Chinese: Calculate the minimum common sum of K arrays after deleting part of the array. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

See all articles