find the all possible sum in a matrix

生来就可爱ヽ(ⅴ<●) 提交于 2020-11-30 01:40:05

问题


I am trying to write a code that find the sum of all the possible numbers in a 2d matrix. But the catch is that you must choose one element from one row.

#include <algorithm>
#include <iostream>
#include <vector>
#include <climits>
#include <math.h>
using namespace std;
int main() { 
    int n;
    cin>>n;
    int array[n][n]={0};
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>array[i][j];
        }
    }
    int power=pow(n,n);
    int sum[power]={0};
    for(int i=0;i<power;i++){
        for(int j=0;j<n;j++){
            for(int l=0;l<n;l++){
                sum[i]=sum[i]+array[j][l];
            }
        }
    }
    for(int i=0;i<power;i++){
        cout<<sum[i]<<" ";
    }
    return 0;
}

this code only brings out the sum of all the elements in the 2d array. So i need help trying to find all the possible sum given one element from each row is chosen for each sum.

2
1 1
1 2
2, 3, 2, 3

this should be the output but it only gives out 5


回答1:


Your core loop is all wrong. If you want sum[i] to contain the values for a given path, you need to treat i as if it were a path through the matrix.

In general, treat i as a number in base n (=2 for your example). That means

i = idx_1 * n^(n-1) + idx_2 * n^(n-2) + ... + idx_n

You can recover the various indexes by repeatedly dividing by n and taking the remainder:

for(uint64_t i=0;i<power;i++){
   sum[i] = 0;
   uint64_t encoded_index = i;
   for (size_t j = 0; j < n; j++) {
       uint64_t index_j = encoded_index % n;
       encoded_index /= n;
       sum[i] += hist[j][index_j];
   }
}

And of course this trick only works if n*n < 2**64 (as uint64_t is 64 bits). For a more general approach see my answer to your other question.



来源:https://stackoverflow.com/questions/61473474/find-the-all-possible-sum-in-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!