I have been stuck with this problem for quite large time. https://www.hackerearth.com/code-monk-bit-manipulation/algorithm/when-the-integers-got-upset/. In short what is says is: There are two arrays A and P of length N. There is a third array Z whose values are calculated as follows:
Z[i]=(A[i] ^ A[i-1] ^ A[i-2]) times P[i] for i ≥ 2, and 0 otherwise.(^ is exor)
We have to rearrange the values in A such that sum of values in Z is minimized.
Eg:A[4]:2 5 4 6
P[4]:1 1 1 1
We can rearrange the values in A as :5 6 2 4 . The corresponding values in Z will be :0 0 1 0 and the sum will be 1.
My approach to this problem in O(n!) but it is exceeding the time limit.There is O(n^2*2^n) approach using dynamic programming and bitmasking.
Note:N<=12.
#include <limits.h>
#include <iostream>
#include<algorithm>
using namespace std;
int func(vector<int> a,vector<int> &p)
{
int res = 0;
// for(int i=0;i<a.size();i++) cout<<a[i]<<" ";
// cout<<endl;
for(int i=2 ; i<a.size() ; i++)
res += ((a[i-2]^a[i-1]^a[i])*p[i]);
// cout<<res<<endl;
return res;
}
int main()
{
int t ; cin>>t ;
while(t--)
{
int n ; cin>> n;
vector<int> a(n) , p(n) ;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++) cin>>p[i];
sort(a.begin() ,a.end());
int res = INT_MAX;
do{
res = min(res,func(a,p));
}while(next_permutation(a.begin() , a.end()));
cout << res << endl;
}
return 0;
}