Any idea to solve this problem in a more efficient way other than comparing it one after another?
------------------------------------------------------------------------------------------------
You’re given n arrays, each array has m integers. There are m^n ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the m smallest sums among them.
Input Format
The first line contains 2 integers n,m .
the following n lines contains m positive integers in each array.
about as fast as it gets is to do a basic find the smallest on each array as it is input and keep a running total of that. By the time all the data is input, you have your answer.
that would net you 2 and 10 for your input, -> 12 is the smallest sum.
do you need all those other sums? If so, you may have to sort each input array, but its the same idea. there, you sort the input and add each (up to m) to a container of results, the [0] is the smallest overall, and so on.
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <cstdlib>
usingnamespace std;
struct Test
{
int value;
vector<int> columns;
booloperator < ( const Test &other ) const
{
if ( value != other.value ) return value < other.value;
for ( int i = 0; i < columns.size(); i++ ) if ( columns[i] != other.columns[i] ) return columns[i] < other.columns[i];
returnfalse;
}
};
int main()
{
int n, m;
cin >> n >> m;
vector< vector<int> > A( n, vector<int>( m ) );
// Read data
for ( int i = 0; i < n; i++ )
{
for ( int j = 0; j < m; j++ ) cin >> A[i][j];
// sort( A[i].begin(), A[i].end() ); // uncomment if data needs sorting
}
// First sum
int sum = 0;
for ( int i = 0; i < n; i++ ) sum += A[i][0];
cout << sum << ' ';
if ( m == 1 ) exit(0);
// Set up first n tests
set<Test> S;
for ( int i = 0; i < n; i++ )
{
vector<int> V(n,0); V[i] = 1;
S.insert( { sum + A[i][1] - A[i][0], V } );
}
// At each stage, remove "best" test and replace in set by its immediate distinct followers
for ( int j = 1; j < m - 1; j++ )
{
Test t = *S.begin();
cout << t.value << ' ';
S.erase( S.begin() );
for ( int i = 0; i < n; i++ )
{
vector<int> V = t.columns; V[i]++;
S.insert( { t.value + A[i][V[i]] - A[i][V[i]-1], V } );
}
}
cout << S.begin()->value << '\n';
}