Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.7 kB
1
Indexable
Never
#include <bits/stdc++.h>

using namespace std;

void display(int a[], int n)  { 
    for (int i = 0; i < n; i++) { 
        cout << a[i] << " "; 
    } 
    cout << endl; 
} 


int calc(int a[], int n, vector <int> given_vec)  { 
    int count = 0;
    int pos = 0;
    for (int k = 0; k < n; k++) {
        for (int j = k; j < n; j++) {
            int sum = 0;
            for (int m = k; m <= j; m++) {
                sum += a[m];
            }
            if (sum == given_vec[pos]) {
                count++;
            }
            pos++;
        }
    }
    return count;
} 

void findPermutations(int a[], int n, vector <int> given_vec) { 
    int best = n;
    int final_arr[n];
    sort(a, a + n); 
    do { 
        int count = calc(a, n, given_vec); 
        if (best > count) {
            best = count;
            copy(a, a+n, final_arr);
        }
    } while (next_permutation(a, a + n)); 
    display(final_arr, n);
} 



int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;

    for (int i = 0; i < t; i++) {
        int n;
        cin >> n;

        int arr[n];
        for (int k = 0; k < n; k++) {
            cin >> arr[k];
        }

        vector <int> given_vec;
        for (int k = 0; k < n; k++) {
            for (int j = k; j < n; j++) {
                int sum = 0;
                for (int m = k; m <= j; m++) {
                    sum += arr[m];
                }
                given_vec.push_back(sum);
            }
        }

        findPermutations(arr, n, given_vec);

    }
    return 0;
}
Leave a Comment