Example

Input

6 3
1 0 0 1 0 1
1 3 2


Output

1
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX 1000100
#define N 30

int memo[MAX], n, m, goal[N], ori[N], goalstate;
queue<int> que;

inline int encode(int arr[]){
  int res = 0;
  for(int i = 0; i < n; i++) res |= (arr[i] << i);
  return res;
}

inline void decode(int state, int res[]){ for(int i = 0; i < n; i++) res[i] = (state >> i) & 1; }

inline int fill_bit(int arr[], int start){
  int sum = 0, res = 0;
  for(int i = 0; i < m; i++){
    if(start) for(int j = 0; j < arr[i]; j++) res |= 1 << (sum + j);
    sum += arr[i];
    start ^= 1;
  }
  return res;
}

int main(){
  while(scanf("%d%d", &n, &m) == 2){
    memset(memo, -1, sizeof(memo));
    
    for(int i = 0; i < n; i++) scanf("%d", ori + i);
    for(int i = 0; i < m; i++) scanf("%d", goal + i);
    
    int state = encode(ori), bits[N];
    que.push(state);
    memo[state] = 0;
    while(!que.empty()){
      state = que.front(); que.pop();
      decode(state, bits);
      
      for(int i = 0; i < n - 1; i++){
        swap(bits[i], bits[i + 1]);
        int nxtstate = encode(bits);
        if(memo[nxtstate] == -1){
          memo[nxtstate] = memo[state] + 1;
          que.push(nxtstate);
        }
        swap(bits[i], bits[i + 1]);
      }
    }
    
    int goal1, goal2;
    goal1 = fill_bit(goal, 0);
    goal2 = fill_bit(goal, 1);
    if(memo[goal1] == -1) printf("%d\n", memo[goal2]);
    else if(memo[goal2] == -1) printf("%d\n", memo[goal1]);
    else printf("%d\n", min(memo[goal1], memo[goal2]));
  }
  return 0;
}