Problem statement:
An N-element permutation is an N-element sequence of distinct numbers from the set {1, 2, ...,n}. For example the sequence 2,1,4,5,3 is a 5-element permutation. P is an N-element permutation. Your task is to sort P in ascending order. But because it is very simple, I have a new rule for you. You have two sequences P and Q. P is an N-element permutation and Q is initially empty and formed by sorting P (i.e. finally Q = 1, 2, 3,... , N). You have to implement N steps to sort P. In the i-th step, P has N-i+1 remaining elements, Q has i-1 elements and you have to choose some x-th element (from the N-i+1 available elements) of P and put it to the left or to the right of Q. The cost of this step is equal to x * i. The total cost is the sum of costs of individual steps. After N steps, Q must be an ascending sequence. Your task is to minimize the total cost.
Input
The first line of the input file is T (T ≤ 10), the number of test cases. Then descriptions of T test cases follow. The description of each test case consists of two lines. The first line contains a single integer N (1 ≤ N ≤ 1000). The second line contains N distinct integers from the set {1, 2, .., N}, the N-element permutation P.
Output
For each test case your program should write one line, containing a single integer - the minimum total cost of sorting.
Input: 1 4 4 1 3 2
Output: 15
My solution :
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int sz;
int n[1001];
map<int,int>pos;
int solve(int i,int a,int b){
if(a==-1&&b==sz) //if all the elements have been moved
return 0;
if(i>sz)
return INT_MAX;
int ret = INT_MAX;
if(a>=0) //select the element from left
ret = min(ret,solve(i+1,a-1,b)+((i+1)*pos[n[a]]));
if(b<sz) //select the element from right
ret = min(ret,solve(i+1,a,b+1)+((i+1)*pos[n[b]]));
return ret;
}
int main()
{
int t;
cin>>t;
while(t--){
cin>>sz;
for(int i=0;i<sz;i++){
int x;
cin>>x;
n[i] = x; //value
pos[x] = i+1; //position of elements of array before sorting
}
sort(n,n+sz); //sorting the array
int ret = INT_MAX;
for(int i=0;i<sz;i++)
ret= min(ret,solve(0,i,i+1));
cout << ret << endl;
}
return 0;
}
This returns wrong answer . What's wrong with my approach ? How can this be fixed ?