// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to merge the subarrays
// arr[l .. m] and arr[m + 1, .. r]
// based on indices[]
void merge(int* indices, int* a, int l,
int mid, int r)
{
int temp_ind[r - l + 1], j = mid + 1;
int i = 0, temp_l = l, k;
while (l <= mid && j <= r) {
// If a[indices[l]] is less than
// a[indices[j]], add indice[l] to temp
if (a[indices[l]] < a[indices[j]])
temp_ind[i++] = indices[l++];
// Else add indices[j]
else
temp_ind[i++] = indices[j++];
}
// Add remaining elements
while (l <= mid)
temp_ind[i++] = indices[l++];
// Add remaining elements
while (j <= r)
temp_ind[i++] = indices[j++];
for (k = 0; k < i; k++)
indices[temp_l++] = temp_ind[k];
}
// Recursive function to divide
// the array into parts
void divide(int* indices, int* a, int l, int r)
{
if (l >= r)
return;
int mid = l / 2 + r / 2;
// Recursive call for elements before mid
divide(indices, a, l, mid);
// Recursive call for elements after mid
divide(indices, a, mid + 1, r);
// Merge the two sorted arrays
merge(indices, a, l, mid, r);
}
// Function to find the number of
// subsequences for each element
void noOfSubsequences(int arr[], int N)
{
int indices[N], i;
for (i = 0; i < N; i++)
indices[i] = i;
// Sorting the indices according
// to array arr[]
divide(indices, arr, 0, N - 1);
// Array to store output numbers
int B[N];
// Initialize subseq
int subseq = 1;
for (i = 0; i < N; i++) {
// B[i] is 2^i
B[indices[i]] = subseq;
// Doubling the subsequences
subseq *= 2;
}
// Print the final output, array B[]
for (i = 0; i < N; i++)
cout << B[i] << " ";
}
// Driver Code
int main()
{
// Given array
int arr[] = { 2, 3, 1 };
// Given length
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
noOfSubsequences(arr, N);
return 0;
}