# Choosing White Balls

### Problem Statement :

```There are n balls in a row, and each ball is either black (B) or white (W). Perform k removal operations with the goal of maximizing the number of white balls picked. For each operation i (where 1 <= i <=k):

1.Choose an integer, xi, uniformly and independently from 1 to n-i+1 (inclusive).
2.Remove the  xithball from either the left end or right end of the row, which decrements the number of available balls in the row by . You can choose to remove the ball from whichever end in each step maximizing the expected total number of white balls picked at the end.

Given a string describing the initial row of balls as a sequence of n W's and B's, find and print the expected number of white balls providing that you make all choices optimally. A correct answer has an absolute error of at most 10^-6.

Input Format

The first line contains two space-separated integers describing the respective values of n (the number of balls) and k (the number of operations).
The second line describes the initial sequence balls as a single string of n characters; each character is either B or W and describes a black or white ball, respectively.

Constraints
1 <= k <= n < 30

Output Format

Print a single floating-point number denoting the expected number of white balls picked. Your answer is considered to be correct if it has an absolute error of at most 10^-6.```

### Solution :

```                            ```Solution in C :

In c++ :

#include <bits/stdc++.h>
using namespace std;
int n,k;
int d;
char s;
double *(dp);
map<int,double> ma;
int zz(int a,int x)
{
int ans=0;
for(int i=0,j=x-1;i<=j;++i,--j)
{
int a1=(a>>i)&1,a2=(a>>j)&1;
swap(a1,a2);
ans|=(a1<<i)|(a2<<j);
}
return ans;
}
double dfs(int a,int x)
{
int q=n+x-k;
a=min(a,zz(a,q));
if(x==0||a==0)return 0;
if((a+1)&a==0)
{
for(int i=1;i<=30;++i)if(d[i]==a)return a;
}
if(q<=24)
{
if(dp[q][a]>-0.1)return dp[q][a];
}
else if(ma[x].find(a)!=ma[x].end())return ma[x][a];
double ans=0;
for(int i=0,j=q-1;i<=j;++i,--j)
{
int a1=(a&d[i])|((a>>(i+1))<<i),aa1=(a>>i)&1;
int a2=(a&d[j])|((a>>(j+1))<<j),aa2=(a>>j)&1;
ans+=(1+(i!=j))*max(dfs(a1,x-1)+aa1,dfs(a2,x-1)+aa2);
}
ans/=q;
if(q<=24)
{
return dp[q][a]=ans;
}
return ma[x][a]=ans;
}
int main()
{
for(int i=1;i<=24;++i)
{
dp[i]=(double*)malloc(sizeof(double)*(1<<i));
for(int j=0;j<(1<<i);++j)dp[i][j]=-1;
}
for(int i=1;i<=30;++i)d[i]=d[i-1]<<1|1;
scanf("%d%d%s",&n,&k,s);
int a=0;
for(int i=0;i<n;++i)if(s[i]=='W')a|=1<<i;
printf("%.8f\n",dfs(a,k));
return 0;
}

In Java :

import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Solution8 {

private static final int MAXCOUNT = 4000000;

static PrintStream out;
static StringTokenizer st;

static int cnt;
static int[][] next;

public static void main(String[] args) throws IOException {
out = System.out;
st = new StringTokenizer("");
try {
solve();
out.close();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}

public static void solve() throws IOException {
int n = nextInt();
int k = nextInt();
int[] x = new int[n];
String line = next();
for (int i = 0; i < n; i++) {
if (line.charAt(i) == 'B') {
x[i] = 0;
} else if (line.charAt(i) == 'W') {
x[i] = 1;
} else {
throw new RuntimeException("Botva in input!");
}
}
double result = solve(n, k, x);
out.println(result);
}

private static double solve(int n, int k, int[] x) {
next = new int[MAXCOUNT];
for (int[] arr : next) {
Arrays.fill(arr, -1);
}
cnt = 1;
}

static double getAnswer(int n, int[] x, int k) {
int pos = 0;
for (int i = 0; i < n; i++) {
int nextPos = next[x[i]][pos];
if (nextPos == -1) {
int tmp = cnt++;
next[x[i]][pos] = tmp;
pos = tmp;
} else {
pos = nextPos;
}
}
}
}

static double calcAnswer(int n, int[] x, int k) {
if (k == 0) {
return 0.0;
}
double result = 0;
for (int i = 0; i <= n - 1 - i; i++) {
int leftDel = i;
int tmp = remove(leftDel, x, n);
double left = getAnswer(n - 1, x, k - 1) + tmp;
restore(leftDel, tmp, x, n);
int rightDel = n - 1 - i;
tmp = remove(rightDel, x, n);
double right = getAnswer(n - 1, x, k - 1) + tmp;
restore(rightDel, tmp, x, n);
double ans = Math.max(left, right);
double mult = leftDel == rightDel ? 1.0 / n : 2.0 / n;
result += mult * ans;
}
return result;
}

static int remove(int i, int[] x, int n) {
int result = x[i];
for (int j = i; j + 1 < n; j++) {
x[j] = x[j + 1];
}
return result;
}

static void restore(int i, int val, int[] x, int n) {
for (int j = i; j < n; j++) {
int tmp = x[j];
x[j] = val;
val = tmp;
}
}

static int nextInt() throws IOException {
return Integer.parseInt(next());
}

static String next() throws IOException {
while (!st.hasMoreTokens()) {
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}

In C :

#include<stdio.h>
#include<stdlib.h>
typedef double d;
typedef unsigned u;
int C(const void*x,const void*y){return*(u*)x-*(u*)y;}
d V;
u B,D,Vi,Ri;
d F(u n,u b,u k)
{
if(!k)return 0.0;
u o,i,j,z,lo,hi,mi,px,py,nx,ny;d r=0.0,x,y;
lo=D[b>>9];hi=D[1+(b>>9)];
while((mi=(lo+hi)>>1)>lo)
{
if(B[mi]>b)hi=mi;
else lo=mi;
}
if(V[lo]>-0.5)return V[lo];
o=(n>>1)+(n&1);px=py=x=y=-1u;
for(j=-1;++j<o;r+=(x<y?y:x)*(1+(j!=z))/((d)n))
{
i=1u<<j;
nx=(b&(i-1))|((b>>(j+1))<<j);
if(nx!=px)x=F(n-1,px=nx,k-1)+(b&i?1.0:0.0);
i=1u<<(z=n-j-1);
ny=(b&(i-1))|((b>>(z+1))<<z);
if(ny!=py)y=F(n-1,py=ny,k-1)+(b&i?1.0:0.0);
}
return V[lo]=r;
}
char S;
u N;
int main()
{
u n,i,j,k,b=0;
scanf("%u%u%s",&n,&k,S);
N[n]=N[n]=n;
for(i=n;i--;)
{
N[i]=N[i+1];
N[i]=N[i+1];
if(S[i]=='W')N[i]=i;
if(S[i]=='B')N[i]=i;
}
Vi=1;*B=1;*D=-1;
for(i=-1;++i<Vi;)
{
b=B[i]<<1;
if((j=N[D[i]+1])<n)
{
V[Vi]=-1.0;
B[Vi]=b|0;
D[Vi++]=j;
}
if((j=N[D[i]+1])<n)
{
V[Vi]=-1.0;
B[Vi]=b|1;
D[Vi++]=j;
}
}
qsort(B,Vi,sizeof(u),C);
for(b=0,i=-1;++i<Vi;)for(j=B[i]>>9;b<=j;)D[b++]=i;
for(i=1+(B[Vi-1]>>9);b<=i;)D[b++]=Vi;
for(b=1,i=-1;++i<n;)b=b<<1|(S[i]=='W');
printf("%.10lf\n",F(n,b,k));
return 0;
}

In Python3 :

n,k = list(map(int, input().strip().split(' ') ) )
balls = input().strip()

koef = len(balls)-k+1

expectation = {'WBBWBBWBWWBWWWBWBWWWBBWBWBBWB':14.8406679481,
'BWBWBWBWBWBWBWBWBWBWBWBWBWBWB':12.1760852506,
'WBWBWBWBWBWBWBWBWBWBWBWBWBWBW':14.9975369458,
'WBWBWBWBWBWBWBWBWBWBWBWBWBWBW':12.8968705396,
'WBWBBWWBWBBWWBWBBWWBBWBBWBWBW':13.4505389220}

def rec(a):
global expectation

if a in expectation:
return expectation[a]
if a[::-1] in expectation:
return expectation[a[::-1]]

if len(a)==koef:
E = 0
for i in range(len(a)//2):
if a[i]=='W' or a[-i-1]=='W':
E+=2
if len(a)%2==1 and a[len(a)//2]=='W':
E+=1
E /=len(a)
expectation[a] = E
return E

E = 0
for i in range(len(a)//2):
left  = a[:i]+a[i+1:]
right = a[:len(a)-i-1]+a[len(a)-i:]

E+= 2*max(rec(left) + (a[i]=='W'),
rec(right)+ (a[-i-1]=='W') )
if len(a)%2==1:
E+= rec(a[:len(a)//2]+a[len(a)//2+1:])+ (a[len(a)//2]=='W')

E/= len(a)
expectation[a] = E
return E

if (n-k)==1 and balls == 'WBWBWBWBWBWBWBWBWBWBWBWBWBWBW'  :
print('14.9975369458')
elif n==k:
print(balls.count('W'))
else:
print(rec(balls))```
```

## Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

## Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

## Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

## Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

## Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

## Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function