Problem:
Problem G:
Flipping Parentheses
A string consisting only of parentheses '(' and ')' is called balanced if it is one of the following.
A string "()" is balanced.
Concatenation of two balanced strings are balanced.
When a string $s$ is balanced, so is the concatenation of three strings "(", $s$, and ")" in this order.
Note that the condition is stronger than merely the numbers of '(' and ')' are equal. For instance, "())(()" is not balanced.
Your task is to keep a string in a balanced state, under a severe condition in which a cosmic ray may flip the direction of parentheses.
You are initially given a balanced string. Each time the direction of a single parenthesis is flipped, your program is notified the position of the changed character in the string. Then, calculate and output the
leftmost
position that, if the parenthesis there is flipped, the whole string gets back to the balanced state. After the string is balanced by changing the parenthesis indicated by your program, next cosmic ray flips another parenthesis, and the steps are repeated several times.
Input
The input consists of a single test case formatted as follows.
$N$ $Q$
$s$
$q_1$
.
.
.
$q_Q$
The first line consists of two integers $N$ and $Q$ ($2 \leq N \leq 300000$, $1 \leq Q \leq 150000$). The second line is a string $s$ of balanced parentheses with length $N$. Each of the following $Q$ lines is an integer $q_i$ ($1 \leq q_i \leq N$) that indicates that the direction of the $q_i$-th parenthesis is flipped.
Output
For each event $q_i$, output the position of the leftmost parenthesis you need to flip in order to get back to the balanced state.
Note that each input flipping event $q_i$ is applied to the string after the previous flip $q_{i−1}$ and its fix.
Sample Input 1
6 3
((()))
4
3
1
Sample Output 1
2
2
1
Sample Input 2
20 9
()((((()))))()()()()
15
20
13
5
3
10
3
17
18
Sample Output 2
2
20
8
5
3
2
2
3
18
In the first sample, the initial state is "((()))". The 4th parenthesis is flipped and the string becomes "(((())". Then, to keep the balance you should flip the 2nd parenthesis and get "()(())". The next flip of the 3rd parenthesis is applied to the last state and yields "())())". To rebalance it, you have to change the 2nd parenthesis again yielding "(()())".

Submitted solutions:

code_snippet: #include<map>
#include<set>
#include<cmath>
#include<queue>
#include<cctype>
#include<cstdio>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<algorithm>
typedef long long LL;
#define MAXN 300010
int N, Q, D, sl[4 * MAXN], sr[4 * MAXN], min[4 * MAXN], a[MAXN], d[4 * MAXN];
char s[MAXN];
void build(int cur, int x, int y) {
	int mid = (x + y) >> 1, ls = cur << 1, rs = ls | 1;
	d[cur] = 0;
	if(x == y) {
		min[cur] = a[x];
		return ;
	}
	build(ls, x, mid), build(rs, mid + 1, y);
	min[cur] = std::min(min[ls], min[rs]);
}
void prepare() {
	for(D = 1; D < N + 2; D <<= 1);
	for(int i = 0; i < D; i ++) {
		if(i >= 1 && i <= N) {
			sl[D + i] = s[i] == '(';
			sr[D + i] = s[i] == ')';
		} else {
			sl[D + i] = sr[D + i] = 0;
		}
	}
	for(int i = D - 1; i >= 0; i --) {
		sl[i] = sl[i << 1] + sl[i << 1 | 1];
		sr[i] = sr[i << 1] + sr[i << 1 | 1];
	}
	build(1, 1, N);
}
void add(int cur, int dd) {
	d[cur] += dd;
	min[cur] += dd;
}
void pushDown(int cur) {
	if(d[cur]) {
		add(cur << 1, d[cur]);
		add(cur << 1 | 1, d[cur]);
		d[cur] = 0;
	}
}
void pushUp(int cur) {
	min[cur] = std::min(min[cur << 1], min[cur << 1 | 1]);
}
void update(int cur, int x, int y, int s, int t, int dd) {
	if(x >= s && y <= t) {
		//printf(":: %d %d %d\n", x, y, dd);
		add(cur, dd);
		return ;
	}
	int mid = (x + y) >> 1, ls = cur << 1, rs = ls | 1;
	pushDown(cur);
	if(mid >= s) {
		update(ls, x, mid, s, t, dd);
	}
	if(mid + 1 <= t) {
		update(rs, mid + 1, y, s, t, dd);
	}
	pushUp(cur);
}
int findOne(int cur, int x, int y) {
	if(x == y) {
		return x;
	}
	int mid = (x + y) >> 1, ls = cur << 1, rs = ls | 1;
	pushDown(cur);
	//printf("findOne:: %d %d %d %d\n", x, y, min[ls], min[rs]);
	if(min[rs] <= 1) {
		return findOne(rs, mid + 1, y);
	}
	return findOne(ls, x, mid);
}
void change(int i, int dd) {
	for(; i > 0; i >>= 1) {
		sl[i] += dd, sr[i] -= dd;
	}
}
int find(int *s, int x, int y) {
	int k = -1;
	for(int i = D + x - 1, j = D + y + 1; i ^ j ^ 1; i >>= 1, j >>= 1) {
		if(~i & 1) {
			if(s[i ^ 1] > 0) {
				k = i ^ 1;
				break;
			}
		}
		if(j & 1) {
			if(s[j ^ 1] > 0) {
				k = j ^ 1;
			}
		}
	}
	for(; k < D;) {
		if(s[k << 1] > 0) {
			k <<= 1;
		} else {
			k = k << 1 | 1;
		}
	}
	return k - D;
}
void process() {
	int x;
	for(int i = 0; i < Q; i ++) {
		scanf("%d", &x);
		if(s[x] == '(') {
			s[x] = ')';
			update(1, 1, N, x, N, -2);
			change(D + x, -1);
			int k = find(sr, 1, N);
			//printf("find (: %d\n", k);
			//printf("): %c\n", s[k]);
			s[k] = '(';
			update(1, 1, N, k, N, 2);
			change(D + k, 1);
			printf("%d\n", k);
		} else {
			s[x] = '(';
			//printf(":: %d %d\n", x, N);
			update(1, 1, N, x, N, 2);
			change(D + x, 1);
			int y = findOne(1, 1, N);
			//printf("fine One: %d\n", y);
			int k = find(sl, y + 1, N);
			//printf("(: %c\n", s[k]);
			s[k] = ')';
			//printf("::: %d\n", k);
			update(1, 1, N, k, N, -2);
			change(D + k, -1);
			printf("%d\n", k);
		}
	}
}
int main() {
	//freopen("test.in", "rb", stdin);
	while(scanf("%d%d",  &N, &Q) == 2) {
		scanf("%s", s + 1);
		a[0] = 0;
		for(int i = 1; i <= N; i ++) {
			a[i] = a[i - 1] + (s[i] == '(' ? 1 : -1);
		}
		prepare();
		process();
	}
	return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 22588
final_rank: 3

code_snippet: #ifndef ONLINE_JUDGE
#define _GLIBCXX_DEBUG //[]で配列外参照をするとエラーにしてくれる。上下のやつがないとTLEになるので注意 ABC311Eのサンプル4みたいなデバック中のTLEは防げないので注意
#endif
#include <bits/stdc++.h>

// #include <atcoder/all>
// using namespace atcoder;
#ifndef ATCODER_INTERNAL_BITOP_HPP
#define ATCODER_INTERNAL_BITOP_HPP 1

#ifdef _MSC_VER
#include <intrin.h>
#endif

#if __cplusplus >= 202002L
#include <bit>
#endif

namespace atcoder
{

  namespace internal
  {

#if __cplusplus >= 202002L

    using std::bit_ceil;

#else

    // @return same with std::bit::bit_ceil
    unsigned int bit_ceil(unsigned int n)
    {
      unsigned int x = 1;
      while (x < (unsigned int)(n))
        x *= 2;
      return x;
    }

#endif

    // @param n `1 <= n`
    // @return same with std::bit::countr_zero
    int countr_zero(unsigned int n)
    {
#ifdef _MSC_VER
      unsigned long index;
      _BitScanForward(&index, n);
      return index;
#else
      return __builtin_ctz(n);
#endif
    }

    // @param n `1 <= n`
    // @return same with std::bit::countr_zero
    constexpr int countr_zero_constexpr(unsigned int n)
    {
      int x = 0;
      while (!(n & (1 << x)))
        x++;
      return x;
    }

  } // namespace internal

} // namespace atcoder

#endif // ATCODER_INTERNAL_BITOP_HPP
#ifndef ATCODER_LAZYSEGTREE_HPP
#define ATCODER_LAZYSEGTREE_HPP 1

#include <algorithm>
#include <cassert>
#include <functional>
#include <vector>

namespace atcoder
{

#if __cplusplus >= 201703L

  template <class S,
            auto op,
            auto e,
            class F,
            auto mapping,
            auto composition,
            auto id>
  struct lazy_segtree
  {
    static_assert(std::is_convertible_v<decltype(op), std::function<S(S, S)>>,
                  "op must work as S(S, S)");
    static_assert(std::is_convertible_v<decltype(e), std::function<S()>>,
                  "e must work as S()");
    static_assert(
        std::is_convertible_v<decltype(mapping), std::function<S(F, S)>>,
        "mapping must work as F(F, S)");
    static_assert(
        std::is_convertible_v<decltype(composition), std::function<F(F, F)>>,
        "compostiion must work as F(F, F)");
    static_assert(std::is_convertible_v<decltype(id), std::function<F()>>,
                  "id must work as F()");

#else

  template <class S,
            S (*op)(S, S),
            S (*e)(),
            class F,
            S (*mapping)(F, S),
            F (*composition)(F, F),
            F (*id)()>
  struct lazy_segtree
  {

#endif

  public:
    lazy_segtree() : lazy_segtree(0) {}
    explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    explicit lazy_segtree(const std::vector<S> &v) : _n(int(v.size()))
    {
      size = (int)internal::bit_ceil((unsigned int)(_n));
      log = internal::countr_zero((unsigned int)size);
      d = std::vector<S>(2 * size, e());
      lz = std::vector<F>(size, id());
      for (int i = 0; i < _n; i++)
        d[size + i] = v[i];
      for (int i = size - 1; i >= 1; i--)
      {
        update(i);
      }
    }

    void set(int p, S x)
    {
      assert(0 <= p && p < _n);
      p += size;
      for (int i = log; i >= 1; i--)
        push(p >> i);
      d[p] = x;
      for (int i = 1; i <= log; i++)
        update(p >> i);
    }

    S get(int p)
    {
      assert(0 <= p && p < _n);
      p += size;
      for (int i = log; i >= 1; i--)
        push(p >> i);
      return d[p];
    }

    S prod(int l, int r)
    {
      assert(0 <= l && l <= r && r <= _n);
      if (l == r)
        return e();

      l += size;
      r += size;

      for (int i = log; i >= 1; i--)
      {
        if (((l >> i) << i) != l)
          push(l >> i);
        if (((r >> i) << i) != r)
          push((r - 1) >> i);
      }

      S sml = e(), smr = e();
      while (l < r)
      {
        if (l & 1)
          sml = op(sml, d[l++]);
        if (r & 1)
          smr = op(d[--r], smr);
        l >>= 1;
        r >>= 1;
      }

      return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f)
    {
      assert(0 <= p && p < _n);
      std::clog << "warning:applied only one element. did you mean apply(L,R,v)?" << std::endl;
      p += size;
      for (int i = log; i >= 1; i--)
        push(p >> i);
      d[p] = mapping(f, d[p]);
      for (int i = 1; i <= log; i++)
        update(p >> i);
    }
    void apply(int l, int r, F f)
    {
      assert(0 <= l && l <= r && r <= _n);
      if (l == r)
        return;

      l += size;
      r += size;

      for (int i = log; i >= 1; i--)
      {
        if (((l >> i) << i) != l)
          push(l >> i);
        if (((r >> i) << i) != r)
          push((r - 1) >> i);
      }

      {
        int l2 = l, r2 = r;
        while (l < r)
        {
          if (l & 1)
            all_apply(l++, f);
          if (r & 1)
            all_apply(--r, f);
          l >>= 1;
          r >>= 1;
        }
        l = l2;
        r = r2;
      }

      for (int i = 1; i <= log; i++)
      {
        if (((l >> i) << i) != l)
          update(l >> i);
        if (((r >> i) << i) != r)
          update((r - 1) >> i);
      }
    }

    template <bool (*g)(S)>
    int max_right(int l)
    {
      return max_right(l, [](S x)
                       { return g(x); });
    }
    template <class G>
    int max_right(int l, G g)
    {
      assert(0 <= l && l <= _n);
      assert(g(e()));
      if (l == _n)
        return _n;
      l += size;
      for (int i = log; i >= 1; i--)
        push(l >> i);
      S sm = e();
      do
      {
        while (l % 2 == 0)
          l >>= 1;
        if (!g(op(sm, d[l])))
        {
          while (l < size)
          {
            push(l);
            l = (2 * l);
            if (g(op(sm, d[l])))
            {
              sm = op(sm, d[l]);
              l++;
            }
          }
          return l - size;
        }
        sm = op(sm, d[l]);
        l++;
      } while ((l & -l) != l);
      return _n;
    }

    template <bool (*g)(S)>
    int min_left(int r)
    {
      return min_left(r, [](S x)
                      { return g(x); });
    }
    template <class G>
    int min_left(int r, G g)
    {
      assert(0 <= r && r <= _n);
      assert(g(e()));
      if (r == 0)
        return 0;
      r += size;
      for (int i = log; i >= 1; i--)
        push((r - 1) >> i);
      S sm = e();
      do
      {
        r--;
        while (r > 1 && (r % 2))
          r >>= 1;
        if (!g(op(d[r], sm)))
        {
          while (r < size)
          {
            push(r);
            r = (2 * r + 1);
            if (g(op(d[r], sm)))
            {
              sm = op(d[r], sm);
              r--;
            }
          }
          return r + 1 - size;
        }
        sm = op(d[r], sm);
      } while ((r & -r) != r);
      return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;
    std::vector<F> lz;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f)
    {
      d[k] = mapping(f, d[k]);
      if (k < size)
        lz[k] = composition(f, lz[k]);
    }
    void push(int k)
    {
      all_apply(2 * k, lz[k]);
      all_apply(2 * k + 1, lz[k]);
      lz[k] = id();
    }
  };

} // namespace atcoder

#endif // ATCODER_LAZYSEGTREE_HPP

using namespace std;
using ll = long long;
ll INF = 2e18;
using P = pair<ll, ll>;
#define pb push_back
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define reprev(i, n) for (ll i = (n) - 1; i >= 0; i--)
#define reps(i, n) for (ll i = 1; i <= (n); i++)
#define for_(i, a, b) for (ll i = (a); i < (b); i++)
#define all(v) v.begin(), v.end()
template <typename T>
inline bool chmin(T &a, const T &b)
{
  bool c = a > b;
  if (c)
    a = b;
  return c;
}
template <typename T>
inline bool chmax(T &a, const T &b)
{
  bool c = a < b;
  if (c)
    a = b;
  return c;
}
template <typename T>
inline T ceil(T a, T b) { return (a + (b - 1)) / b; }
// using mint = modint998244353;
//  using mint = modint1000000007;
//  using mint = static_modint<10>;//使うときはコメントアウトを外す
template <typename T>
using vc = vector<T>;
template <class T>
istream &operator>>(istream &i, vc<T> &v)
{
  rep(j, size(v)) i >> v[j];
  return i;
}
template <class T>
ostream &operator<<(ostream &o, const vc<T> &v)
{
  rep(j, size(v))
  {
    if (j)
      o << " ";
    o << v[j];
  }
  o << endl;
  return o;
}
// 区間加算・区間最小値取得
// 値の乗せ方:https://betrue12.hateblo.jp/entry/2020/09/22/194541
// チートシート:https://betrue12.hateblo.jp/entry/2020/09/23/005940
using S = ll;
using F = ll;

S op(S a, S b) { return std::min(a, b); }
S e() { return INF; }
S mapping(F f, S x) { return f + x; }
F composition(F f, F g) { return f + g; }
F id() { return 0; }
using lazy_seg = atcoder::lazy_segtree<S, op, e, F, mapping, composition, id>;
S target = 2;
// target以上の最小の値を持つ区間の左端を返す
// ref:https://qiita.com/recuraki/items/ae8e965b84f0e5443dc5
bool min_left(S x)
{
  return x >= target;
}
int main()
{
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  // ref:https://rsk0315.hatenablog.com/entry/2020/05/09/170315
  ll N;
  cin >> N;
  ll Q;
  cin >> Q;
  string S_;
  cin >> S_;
  vc<ll> cnt(N, 0);
  rep(i, N)
  {
    if (i != 0)
    {
      cnt[i] = cnt[i - 1];
    }
    if (S_[i] == '(')
    {
      cnt[i]++;
    }
    else
    {
      cnt[i]--;
    }
  }
  lazy_seg seg(cnt);
  set<ll> st;
  rep(i, N)
  {
    if (S_[i] == ')')
    {
      st.insert(i);
    }
  }
  rep(i, Q)
  {
    ll t;
    cin >> t;
    t--;
    if (S_[t] == '(')
    {
      S_[t] = ')';
      st.insert(t);
      seg.apply(t, N, -2);
      cout << *st.begin() + 1 << endl;
      S_[*st.begin()] = '(';
      seg.apply(*st.begin(), N, 2);
      st.erase(st.begin());
    }
    else
    {
      S_[t] = '(';
      st.erase(t);
      seg.apply(t, N, 2);
      ll idx = seg.min_left<min_left>(N);
      cout << idx + 1 << endl;
      S_[idx] = ')';
      seg.apply(idx, N, -2);
      st.insert(idx);
    }
  }
  //  cout << ans << endl;
  return 0;
}
accuracy: 1
time_ms: 400
memory_kb: 24956
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define all(v) (v).begin(),(v).end()
#define pb(a) push_back(a)
#define rep(i, n) for(int i=0;i<n;i++)
#define foa(e, v) for(auto&& e : v)
using ll = long long;
const ll MOD7 = 1000000007, MOD998 = 998244353, INF = (1LL << 60);
#define dout(a) cout<<fixed<<setprecision(10)<<a<<endl;

// base: 918715
unsigned int bit_ceil(unsigned int n) {
   unsigned int x = 1;
   while(x < (unsigned int)(n)) x *= 2;
   return x;
}
int countr_zero(unsigned int n) { return __builtin_ctz(n); }
constexpr int countr_zero_constexpr(unsigned int n) {
   int x = 0;
   while(!(n & (1 << x))) x++;
   return x;
}
template<class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S), F (*composition)(F, F), F (*id)()>
struct lazy_segtree {
   public:
   lazy_segtree() : lazy_segtree(0) {}
   explicit lazy_segtree(int n) : lazy_segtree(vector<S>(n, e())) {}
   explicit lazy_segtree(const vector<S>& v) : _n(int(v.size())) {
      size = (int)bit_ceil((unsigned int)(_n));
      log = countr_zero((unsigned int)size);
      d = vector<S>(2 * size, e());
      lz = vector<F>(size, id());
      for(int i = 0; i < _n; i++) d[size + i] = v[i];
      for(int i = size - 1; i >= 1; i--) { update(i); }
   }
   void set(int p, S x) {
      // assert(0 <= p && p < _n);
      p += size;
      for(int i = log; i >= 1; i--) push(p >> i);
      d[p] = x;
      for(int i = 1; i <= log; i++) update(p >> i);
   }

   S get(int p) {
      // assert(0 <= p && p < _n);
      p += size;
      for(int i = log; i >= 1; i--) push(p >> i);
      return d[p];
   }

   S prod(int l, int r) {
      // assert(0 <= l && l <= r && r <= _n);
      if(l == r) return e();

      l += size;
      r += size;

      for(int i = log; i >= 1; i--) {
         if(((l >> i) << i) != l) push(l >> i);
         if(((r >> i) << i) != r) push((r - 1) >> i);
      }

      S sml = e(), smr = e();
      while(l < r) {
         if(l & 1) sml = op(sml, d[l++]);
         if(r & 1) smr = op(d[--r], smr);
         l >>= 1;
         r >>= 1;
      }

      return op(sml, smr);
   }

   void apply(int l, int r, F f) {
      assert(0 <= l && l <= r && r <= _n);
      if(l == r) return;

      l += size;
      r += size;

      for(int i = log; i >= 1; i--) {
         if(((l >> i) << i) != l) push(l >> i);
         if(((r >> i) << i) != r) push((r - 1) >> i);
      }

      {
         int l2 = l, r2 = r;
         while(l < r) {
            if(l & 1) all_apply(l++, f);
            if(r & 1) all_apply(--r, f);
            l >>= 1;
            r >>= 1;
         }
         l = l2;
         r = r2;
      }

      for(int i = 1; i <= log; i++) {
         if(((l >> i) << i) != l) update(l >> i);
         if(((r >> i) << i) != r) update((r - 1) >> i);
      }
   }

   template<class G> int max_right(int l, G g) {
      // assert(0 <= l && l <= _n);
      // assert(g(e()));
      if(l == _n) return _n;
      l += size;
      for(int i = log; i >= 1; i--) push(l >> i);
      S sm = e();
      do {
         while(l % 2 == 0) l >>= 1;
         if(!g(op(sm, d[l]))) {
            while(l < size) {
               push(l);
               l = (2 * l);
               if(g(op(sm, d[l]))) {
                  sm = op(sm, d[l]);
                  l++;
               }
            }
            return l - size;
         }
         sm = op(sm, d[l]);
         l++;
      } while((l & -l) != l);
      return _n;
   }  // d93691

   template<class G> int min_left(int r, G g) {
      // assert(0 <= r && r <= _n);
      // assert(g(e()));
      if(r == 0) return 0;
      r += size;
      for(int i = log; i >= 1; i--) push((r - 1) >> i);
      S sm = e();
      do {
         r--;
         while(r > 1 && (r % 2)) r >>= 1;
         if(!g(op(d[r], sm))) {
            while(r < size) {
               push(r);
               r = (2 * r + 1);
               if(g(op(d[r], sm))) {
                  sm = op(d[r], sm);
                  r--;
               }
            }
            return r + 1 - size;
         }
         sm = op(d[r], sm);
      } while((r & -r) != r);
      return 0;
   }  // c9a7eb

   private:
   int _n, size, log;
   vector<S> d;
   vector<F> lz;

   void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
   void all_apply(int k, F f) {
      d[k] = mapping(f, d[k]);
      if(k < size) lz[k] = composition(f, lz[k]);
   }
   void push(int k) {
      all_apply(2 * k, lz[k]);
      all_apply(2 * k + 1, lz[k]);
      lz[k] = id();
   }
};


ll op(ll a, ll b) { return min(a, b); }
ll e() { return INF; }
ll mapping(ll f, ll x) { return f + x; }
ll composition(ll f, ll g) { return f + g; }
ll id() { return 0; }

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, q;
    cin >> n >> q;
    string s; cin >> s;
    set<int> rights;

    vector<ll> cnt(n + 1, 0);
    for(int i = n - 1; i >= 0; i --) {
        if(s[i] == '(') {
            cnt[i] = cnt[i + 1] - 1;
        } else {
            cnt[i] = cnt[i + 1] + 1;
            rights.insert(i);
        }
    }
    lazy_segtree<ll, op, e, ll, mapping, composition, id> seg(cnt);
    rep(i, q) {
        int x; cin >> x;
        x --;
        if(s[x] == '(') {
            seg.apply(0, x + 1, 2);
            s[x] = ')';
            rights.insert(x);
            int y = *rights.begin();
            rights.erase(rights.begin());
            cout << y + 1 << endl;
            seg.apply(0, y + 1, -2);
            s[y] = '(';
        } else {
            seg.apply(0, x + 1, -2);
            s[x] = '(';
            rights.erase(x);
            int y = seg.min_left(n, [](ll x) { return x >= 0LL; }) - 1;
            cout << y + 1 << endl;
            rights.insert(y);
            seg.apply(0, y + 1, 2);
            s[y] = ')';
        }
    }
    return 0;
}
accuracy: 1
time_ms: 290
memory_kb: 24996
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9 + 10;
const ll INFL = 4e18;

template <typename Monoid>
struct SegTree {
    using Type = typename Monoid::Type;

    SegTree() = default;
    SegTree(int n) {
        this->n = n;
        dat.assign(n << 1, Monoid::id());
    }
    SegTree(const vector<Type>& v) {
        this->n = v.size();
        dat.assign(n << 1, Monoid::id());
        for (int i = 0; i < n; i++) dat[i + n] = v[i];
        for (int i = n - 1; i > 0; i--) dat[i] = Monoid::op(dat[i << 1], dat[i << 1 | 1]);
    }

    void set(int i, Type x) {
        i += n;
        dat[i] = x;
        while (i >>= 1) dat[i] = Monoid::op(dat[i << 1], dat[i << 1 | 1]);
    }
    Type fold(int l, int r) {
        Type retl = Monoid::id(), retr = Monoid::id();
        l += n, r += n;
        while (l < r) {
            if (l & 1) retl = Monoid::op(retl, dat[l++]);
            if (r & 1) retr = Monoid::op(dat[--r], retr);
            l >>= 1, r >>= 1;
        }
        return Monoid::op(retl, retr);
    }
    template <typename F>
    int find_right(int l, F f) {
        assert(f(Monoid::id()));
        if (l == n) return n;
        l += n;
        int r = n + n;
        vector<int> cand_l, cand_r;
        while (l < r) {
            if (l & 1) cand_l.push_back(l++);
            if (r & 1) cand_r.push_back(--r);
            l >>= 1, r >>= 1;
        }
        vector<int> cand = cand_l;
        reverse(cand_r.begin(), cand_r.end());
        cand.insert(cand.end(), cand_r.begin(), cand_r.end());
        Type val = Monoid::id();
        for (int i : cand) {
            if (f(Monoid::op(val, dat[i]))) {
                val = Monoid::op(val, dat[i]);
            } else {
                while (i < n) {
                    i <<= 1;
                    if (f(Monoid::op(val, dat[i]))) {
                        val = Monoid::op(val, dat[i]);
                        i |= 1;
                    }
                }
                return i - n;
            }
        }
        return n;
    }
    template <typename F>
    int find_left(int r, F f) {
        assert(f(Monoid::id()));
        if (r == 0) return 0;
        r += n;
        int l = n;
        vector<int> cand_l, cand_r;
        while (l < r) {
            if (l & 1) cand_l.push_back(l++);
            if (r & 1) cand_r.push_back(--r);
            l >>= 1, r >>= 1;
        }
        vector<int> cand = cand_r;
        reverse(cand_l.begin(), cand_l.end());
        cand.insert(cand.end(), cand_l.begin(), cand_l.end());
        Type val = Monoid::id();
        for (int i : cand) {
            if (f(Monoid::op(dat[i], val))) {
                val = Monoid::op(dat[i], val);
            } else {
                while (i < n) {
                    i = (i << 1) | 1;
                    if (f(Monoid::op(dat[i], val))) {
                        val = Monoid::op(dat[i], val);
                        i ^= 1;
                    }
                }
                return i - n + 1;
            }
        }
        return 0;
    }

    int size() { return n; }
    Type operator[](int i) { return dat[i + n]; }

private:
    int n;
    vector<Type> dat;
};

template <typename T, T max_value = INF>
struct MinMonoid {
    using Type = T;
    static Type id() { return max_value; }
    static Type op(const Type& a, const Type& b) { return min(a, b); }
};

template <typename T, T min_value = -INF>
struct MaxMonoid {
    using Type = T;
    static Type id() { return min_value; }
    static Type op(const Type& a, const Type& b) { return max(a, b); }
};

template <typename T>
struct SumMonoid {
    using Type = T;
    static Type id() { return 0; }
    static Type op(const Type& a, const Type& b) { return a + b; }
};

template <typename T>
struct PairSumMonoid {
    using Type = pair<T, int>;
    static Type id() { return make_pair(T(0), 0); }
    static Type op(const Type& a, const Type& b) { return {a.first + b.first, a.second + b.second}; }
};

template <typename T, T max_value = INF>
struct RangeMin {
    using Type = struct SegTree<MinMonoid<T, max_value>>;
};

template <typename T, T min_value = -INF>
struct RangeMax {
    using Type = struct SegTree<MaxMonoid<T, min_value>>;
};

template <typename T>
struct RangeSum {
    using Type = struct SegTree<SumMonoid<T>>;
};

/*
    考察
    ( -> ) : 一番左の)を(にする
    ) -> ( : 左側の累積和+min(右側の累積和)が1以上の最左の(を)にする
*/

struct Data {
    // 累積和,累積和のmin
    int sum, min;
};

struct Monoid {
    using Type = Data;
    static Type op(const Type& l, const Type& r) {
        auto [lsm, lmn] = l;
        auto [rsm, rmn] = r;
        return Data{lsm + rsm, min(lmn, lsm + rmn)};
    }
    static Type id() { return {0, INF}; }
};

int main() {
    int N, Q;
    cin >> N >> Q;
    vector<Data> A(N);
    for (int i = 0; i < N; i++) {
        char c;
        cin >> c;
        if (c == '(') {
            A[i] = {1, 0};
        } else {
            A[i] = {-1, -1};
        }
    }

    SegTree<Monoid> seg(A);
    RangeSum<int>::Type rs(N);
    set<int> st;
    for (int i = 0; i < N; i++) {
        if (A[i].sum == 1) {
            rs.set(i, 1);
        } else {
            st.insert(i);
        }
    }

    auto Get = [&](int k) {
        auto f = [&](int x) { return x <= k; };
        return rs.find_right(0, f);
    };
    auto Flip1 = [&](int x) {
        seg.set(x, {1, 0});
        st.erase(x);
        rs.set(x, 1);
    };
    auto Flip2 = [&](int y) {
        seg.set(y, {-1, -1});
        st.insert(y);
        rs.set(y, 0);
    };
    auto Show = [&]() {
        for (int i = 0; i < N; i++) {
            if (rs[i] == 1) {
                cout << '(';
            } else {
                cout << ')';
            }
        }
        cout << endl;
    };

    while (Q--) {
        int p;
        cin >> p;
        p--;

        if (rs[p] == 1) {
            Flip2(p);
            int q = *st.begin();
            Flip1(q);
            cout << q + 1 << '\n';
        } else {
            Flip1(p);
            int sz = rs.fold(0, N);

            int lo = -1, hi = sz;
            while (hi - lo > 1) {
                int mid = (hi + lo) / 2;
                int k = Get(mid);

                Flip2(k);
                auto [sm, mn] = seg.fold(0, N);
                bool ok = mn >= 0 && sm == 0;
                Flip1(k);

                if (ok) {
                    hi = mid;
                } else {
                    lo = mid;
                }
            }

            cout << Get(hi) + 1 << '\n';
            Flip2(Get(hi));
        }
    }
}
accuracy: 1
time_ms: 1480
memory_kb: 19620
final_rank: 16

code_snippet: #include <bits/stdc++.h>

#define N 300010

using namespace std;

int mn[N * 4], psh[N * 4], sum[N];

set<int> L, R;
string str;

void push(int v)
{
    mn[v + v] += psh[v];
    mn[v + v + 1] += psh[v];
    psh[v + v] += psh[v];
    psh[v + v + 1] += psh[v];
    psh[v] = 0;
}

void bld(int v, int tl, int tr)
{
    if(tl==tr) {
        psh[v] = 0;
        mn[v] = sum[tl];
        return;
    }

    int md = (tl + tr) / 2;
    bld(v + v, tl, md);
    bld(v + v + 1, md + 1, tr);
    mn[v] = min(mn[v + v], mn[v + v + 1]);
}

void upd(int v, int tl, int tr, int l, int r, int x)
{
    if(l <= tl && tr <= r) {
        mn[v] += x;
        psh[v] += x;
        return;
    }
    if(tr < l || r < tl)
        return;

    push(v);
    int md = (tl + tr) / 2;
    upd(v + v, tl, md, l, r, x);
    upd(v + v + 1, md + 1, tr, l, r, x);

    mn[v] = min(mn[v + v], mn[v + v + 1]);
}

int qr(int v, int tl, int tr, int l, int r)
{
    if(r < tl || tr < l)
        return 1e9;

    if(l <= tl && tr <= r)
        return mn[v];

    push(v);

    int md = (tl + tr) / 2;
    return min(qr(v + v, tl, md, l, r), qr(v + v + 1, md + 1, tr, l, r));
}

int n, q;
void flip(int pos)
{
    if(str[pos]=='(')
    {
        str[pos]=')';
        L.erase(pos);
        R.insert(pos);
        upd(1, 0, n - 1, pos, n - 1, -2);
    }
    else
    {
        str[pos]='(';
        R.erase(pos);
        L.insert(pos);
        upd(1, 0, n-1, pos, n - 1, 2);
    }
}

int main() {
    cin >> n >> q >> str;

    for(int i = 0; i < n; i++)
    {
        if (str[i] == '(')
            sum[i]++;
                else sum[i]--;

        if (i)
            sum[i] += sum[i - 1];

        if(str[i]=='(')
           L.insert(i);
                else R.insert(i);
    }

    bld(1, 0, n - 1);

    for(int i = 0; i < q; i++)
    {
        int pos;
        cin >> pos;
        pos--;

        if(str[pos]=='(')
        {
            flip(pos);
            int ans = *(R.begin());
            cout << ans + 1 << endl;
            flip(ans);
        }
        else
        {
            flip(pos);
            int l = 0, r = n;

            while(l < r)
            {
                int md=(l + r) / 2;

                if(qr(1, 0,n - 1, md, pos) >= 2)
                    r = md;
                else
                    l = md + 1;
            }

            int res = *(L.lower_bound(l));
            flip(res);

            cout << res + 1 << endl;
        }
    }
}
accuracy: 1
time_ms: 890
memory_kb: 26708
final_rank: 15

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

template <typename M, typename N, M (*f)(M, M), M (*g)(M, N), N (*h)(N, N),
          M (*m1)(), N (*n1)()>
class LazySegmentTree {
    int n, sz, height;
    vector<M> data;
    vector<N> lazy;
    void update(int k) {
        data[k] = f(data[k * 2], data[k * 2 + 1]);
    }
    void apply(int k, N x) {
        data[k] = g(data[k], x);
        if (k < sz)
            lazy[k] = h(lazy[k], x);
    }
    void down(int k) {
        apply(k * 2, lazy[k]);
        apply(k * 2 + 1, lazy[k]);
        lazy[k] = n1();
    }

  public:
    LazySegmentTree(int n = 0) : LazySegmentTree(vector<M>(n, m1())) {}
    LazySegmentTree(const vector<M> &a) : n(SZ(a)) {
        sz = 1, height = 0;
        while (sz < (int)a.size())
            sz <<= 1, height++;
        data.assign(2 * sz, m1());
        lazy.assign(sz, n1());
        rep(i, 0, a.size()) data[sz + i] = a[i];
        for (int i = sz - 1; i; i--)
            update(i);
    }
    M operator[](int k) const {
        k += sz;
        rrep(i, 1, height + 1) down(k >> i);
        return data[k];
    }
    vector<M> get() {
        rep(k, 1, sz) down(k);
        return {data.begin() + sz, data.begin() + sz + n};
    }
    void set(int k, M x) {
        k += sz;
        for (int i = height; i; i--)
            down(k >> i);
        data[k] = x;
        for (int i = 1; i <= height; i++)
            update(k >> i);
    }
    void update(int L, int R, N x) {
        if (L >= R)
            return;
        L += sz, R += sz;
        for (int i = height; i; i--) {
            if (((L >> i) << i) != L)
                down(L >> i);
            if (((R >> i) << i) != R)
                down((R - 1) >> i);
        }
        int lb = L, rb = R;
        while (L < R) {
            if (L & 1)
                apply(L++, x);
            if (R & 1)
                apply(--R, x);
            L >>= 1;
            R >>= 1;
        }
        L = lb, R = rb;
        for (int i = 1; i <= height; i++) {
            if (((L >> i) << i) != L)
                update(L >> i);
            if (((R >> i) << i) != R)
                update((R - 1) >> i);
        }
    }
    M query(int L, int R) {
        if (L >= R)
            return m1();
        L += sz, R += sz;
        for (int i = height; i; i--) {
            if (((L >> i) << i) != L)
                down(L >> i);
            if (((R >> i) << i) != R)
                down((R - 1) >> i);
        }
        M lb = m1(), rb = m1();
        while (L < R) {
            if (L & 1)
                lb = f(lb, data[L++]);
            if (R & 1)
                rb = f(data[--R], rb);
            L >>= 1;
            R >>= 1;
        }
        return f(lb, rb);
    }
    template <class F> int max_right(int L, F ch) {
        if (L == n)
            return n;
        L += sz;
        rrep(i, 1, height + 1) down(L >> i);
        M sum = m1();
        do {
            while (L % 2 == 0)
                L >>= 1;
            if (!ch(f(sum, data[L]))) {
                while (L < sz) {
                    down(L);
                    L <<= 1;
                    if (ch(f(sum, data[L])))
                        sum = f(sum, data[L++]);
                }
                return L - sz;
            }
            sum = f(sum, data[L++]);
        } while ((L & -L) != L);
        return n;
    }
    template <class F> int min_left(int R, F ch) {
        if (R == 0)
            return 0;
        R += sz;
        rrep(i, 1, height + 1) down((R - 1) >> i);
        M sum = m1();
        do {
            R--;
            while (R > 1 and (R & 1))
                R >>= 1;
            if (!ch(f(data[R], sum))) {
                while (R < sz) {
                    down(R);
                    R = (R * 2 + 1);
                    if (ch(f(data[R], sum))) {
                        sum = f(data[R--], sum);
                    }
                }
                return R + 1 - sz;
            }
            sum = f(data[R], sum);
        } while ((R & -R) != R);
        return 0;
    }
};

/**
 * @brief Lazy Segment Tree
 */

ll f(ll A, ll B) {return min(A,B);}
ll g(ll A, ll B) {return A+B;}
ll h(ll A, ll B) {return A+B;}
ll e1() {return INF;}
ll e2() {return 0;}

int main() {
    int N, Q;
    cin >> N >> Q;
    vector<ll> A(N);
    set<int> st;
    rep(i,0,N) {
        char C;
        cin >> C;
        if (C == '(') A[i] = 1;
        else A[i] = -1, st.insert(i);
    }
    vector<ll> AS(N+1,0);
    rep(i,0,N) AS[i+1] = AS[i] + A[i];
    LazySegmentTree<ll,ll,f,g,h,e1,e2> Seg(AS);
    while(Q--) {
        int X;
        cin >> X;
        X--;
        if (A[X] == -1) {
            st.erase(X);
            A[X] = 1;
            Seg.update(X+1, N+1, 2);
            int Left = Seg.min_left(N+1, [&](ll X){return X >= 2;}) - 1;
            cout << Left + 1 << endl;
            st.insert(Left);
            A[Left] = -1;
            Seg.update(Left+1, N+1, -2);
        }
        else {
            st.insert(X);
            A[X] = -1;
            Seg.update(X+1, N+1, -2);
            auto it = st.begin();
            cout << (*it) + 1 << endl;
            Seg.update((*it) + 1, N+1, 2);
            A[*it] = 1;
            st.erase(it);
        }
    }
}
accuracy: 1
time_ms: 320
memory_kb: 27100
final_rank: 9

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 1 "cp-library/src/data_structure/lazy_segtree.hpp"
template < class A > struct lazy_segtree {
  public:
    using V = typename A::value_structure;
    using S = typename V::set;
    using O = typename A::operator_structure;
    using F = typename O::set;
    int _n, size, log;
    vector< S > d;
    vector< F > lz;

    void update(int k) { d[k] = V::op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f) {
        d[k] = A::op(d[k], f);
        if(k < size) lz[k] = O::op(lz[k], f);
    }
    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = O::id();
    }
    int ceil_pow2(int n) {
        int x = 0;
        while((1U << x) < uint(n)) x++;
        return x;
    }

    lazy_segtree() : lazy_segtree(0) {}
    lazy_segtree(int n) : lazy_segtree(vector< S >(n, V::id())) {}
    lazy_segtree(int n, S s) : lazy_segtree(vector< S >(n, s)) {}
    lazy_segtree(const vector< S > v) : _n(int(v.size())) {
        log = ceil_pow2(_n);
        size = 1 << log;
        d = vector< S >(2 * size, V::id());
        lz = vector< F >(size, O::id());
        for(int i = 0; i < _n; i++) d[size + i] = v[i];
        for(int i = size - 1; i >= 1; i--) update(i);
    }

    void set(int i, S x) {
        assert(0 <= i && i < _n);
        i += size;
        for(int p = log; p >= 1; p--) push(i >> p);
        d[i] = x;
        for(int p = 1; p <= log; p++) update(i >> p);
    }
    S get(int i) {
        assert(0 <= i && i < _n);
        i += size;
        for(int p = log; p >= 1; p--) push(i >> p);
        return d[i];
    }
    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if(l == r) return V::id();
        l += size, r += size;
        for(int i = log; i >= 1; i--) {
            if(((l >> i) << i) != l) push(l >> i);
            if(((r >> i) << i) != r) push(r >> i);
        }
        S sml = V::id(), smr = V::id();
        while(l < r) {
            if(l & 1) sml = V::op(sml, d[l++]);
            if(r & 1) smr = V::op(d[--r], smr);
            l >>= 1, r >>= 1;
        }
        return V::op(sml, smr);
    }
    S all_prod() { return d[1]; }
    void apply(int i, F f) {
        assert(0 <= i && i < _n);
        i += size;
        for(int p = log; p >= 1; p--) push(i >> p);
        d[i] = A::op(d[i], f);
        for(int p = 1; p <= log; p++) update(i >> p);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if(l == r) return;
        l += size, r += size;
        for(int i = log; i >= 1; i--) {
            if(((l >> i) << i) != l) push(l >> i);
            if(((r >> i) << i) != r) push((r - 1) >> i);
        }
        {
            int l2 = l, r2 = r;
            while(l < r) {
                if(l & 1) all_apply(l++, f);
                if(r & 1) all_apply(--r, f);
                l >>= 1, r >>= 1;
            }
            l = l2, r = r2;
        }
        for(int i = 1; i <= log; i++) {
            if(((l >> i) << i) != l) update(l >> i);
            if(((r >> i) << i) != r) update((r - 1) >> i);
        }
    }
    template < class G > int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(V::id()));
        if(l == _n) return _n;
        l += size;
        for(int i = log; i >= 1; i--) push(l >> i);
        S sm = V::id()();
        do {
            while(l % 2 == 0) l >>= 1;
            if(!g(V::op(sm, d[l]))) {
                while(l < size) {
                    push(l);
                    l = 2 * l;
                    if(g(V::op(sm, d[l]))) {
                        sm = V::op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = V::op(sm, d[l]);
            l++;
        } while((l & -l) != l);
        return _n;
    }
    template < class G > int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(V::id()));
        if(r == 0) return 0;
        r += size;
        for(int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = V::id();
        do {
            r--;
            while(r > 1 && (r % 2)) r >>= 1;
            if(!g(V::op(d[r], sm))) {
                while(r < size) {
                    push(r);
                    r = 2 * r + 1;
                    if(g(V::op(d[r], sm))) {
                        sm = V::op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = V::op(d[r], sm);
        } while((r & -r) != r);
        return 0;
    }
};
#line 3 "cp-library/src/algebra/minmax.hpp"

template < class T > class min_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return std::min(l, r); }
    static constexpr T id() { return std::numeric_limits< T >::max(); }
    static constexpr bool comm = true;
};

template < class T > class max_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return std::max(l, r); }
    static constexpr T id() { return std::numeric_limits< T >::min(); }
    static constexpr bool comm = true;
};
#line 1 "cp-library/src/algebra/sum.hpp"
template < class T > class sum_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return l + r; }
    static constexpr T id() { return T(0); }
    static constexpr T inv(const T &x) { return -x; }
    static constexpr T pow(const T &x, const ll n) { return x * n; }
    static constexpr bool comm = true;
};
#line 5 "cp-library/src/algebra/range_add_range_minmax.hpp"

template < class T > class range_add_range_min {
  public:
    using value_structure = min_monoid< T >;
    using operator_structure = sum_monoid< T >;
  private:
    using S = typename value_structure::set;
    using F = typename operator_structure::set;
  public:
    static constexpr S op(const S& l, const F& r) {
        return S(l + r);
    }
};

template < class T > class range_add_range_max {
  public:
    using value_structure = max_monoid< T >;
    using operator_structure = sum_monoid< T >;
  private:
    using S = typename value_structure::set;
    using F = typename operator_structure::set;
  public:
    static constexpr S op(const S& l, const F& r) {
        return S(l + r);
    }
};
#line 5 "A.cpp"

int main() {
    int N = in(), Q = in();
    string str = in();
    vector<int> A(N);
    for(int i : rep(N)) A[i] = (str[i] == '(' ? +1 : -1);
    set<int> minus;
    for(int i : rep(N)) if(A[i] == -1) minus.insert(i);
    vector<int> V = A;
    for(int i : rep(1, N)) V[i] += V[i - 1];
    lazy_segtree<range_add_range_min<int>> seg(V);

    auto push = [&](int i) {
        assert(0 <= i and i < N);
        if(A[i] == +1) {
            A[i] = -1;
            seg.apply(i, N, -2);
            minus.insert(i);
        } else {
            A[i] = +1;
            seg.apply(i, N, +2);
            minus.erase(i);
        }
    };

    for(int _ : rep(Q)) {
        int p = in(); p--;
        if(A[p] == +1) {
            push(p);
            const int i = *minus.begin();
            print(i + 1);
            push(i);
        } else {
            push(p);
            const int i = seg.min_left(N, [&](int x) { return x >= 2; });
            print(i + 1);
            push(i);
        }
    }
}
accuracy: 1
time_ms: 190
memory_kb: 20176
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep(i, n) for (int i = 0; i < (n); i++)
#define per(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep2(i, l, r) for (int i = (l); i < (r); i++)
#define per2(i, l, r) for (int i = (r)-1; i >= (l); i--)
#define each(e, x) for (auto &e : x)
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define eb emplace_back
#define MM << ' ' <<
#define TT template <typename T>
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

TT bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }
TT bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }

TT using minheap = priority_queue<T, vector<T>, greater<T>>;
TT using maxheap = priority_queue<T>;

TT void print(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << (i == n - 1 ? '\n' : ' ');
    if (n == 0) cout << '\n';
}

TT void printn(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << '\n';
}

TT void rearrange(vector<T> &v) {
    sort(all(v));
    v.erase(unique(all(v)), end(v));
}

TT int lb(vector<T> &v, T x) { return lower_bound(all(v), x) - begin(v); }
TT int ub(vector<T> &v, T x) { return upper_bound(all(v), x) - begin(v); }

const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;

struct io_setup {
    io_setup() {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout << fixed << setprecision(15);
    }
} io_setup;

template <typename T, typename O>
struct LazySegmentTree {
    using F = function<T(T, T)>;
    using G = function<T(T, O)>;
    using H = function<O(O, O)>;
    vector<T> data;
    vector<O> lazy;
    int n;
    const F f;
    const G g;
    const H h;
    const T e1;
    const O e2;

    LazySegmentTree(vector<T> v, F f, G g, H h, T e1, O e2) : f(f), g(g), h(h), e1(e1), e2(e2) {
        int m = v.size();
        n = 1;
        while (n < m) n *= 2;
        data.assign(2 * n, e1);
        rep(i, m) data[n + i] = v[i];
        lazy.assign(2 * n, e2);
        per2(i, 1, n) data[i] = f(data[2 * i], data[2 * i + 1]);
    }

    LazySegmentTree(int m, T x, F f, G g, H h, T e1, O e2) : LazySegmentTree(vector<T>(m, x), f, g, h, e1, e2) {}

    T get(int k) { return g(data[k], lazy[k]); }

    void eval(int k) {
        data[k] = get(k);
        rep(i, 2) lazy[2 * k + i] = h(lazy[2 * k + i], lazy[k]);
        lazy[k] = e2;
    }

    T update(int l, int r, O x, int k = 1, int L = 0, int R = -1) {
        if (R == -1) R = n;
        // if の中身要注意！
        if (r <= L || R <= l) return get(k);
        if (l <= L && R <= r) {
            lazy[k] = h(lazy[k], x);
            return get(k);
        }
        eval(k);
        int M = (L + R) / 2;
        return data[k] = f(update(l, r, x, 2 * k, L, M), update(l, r, x, 2 * k + 1, M, R));
    }

    T query(int l, int r, int k = 1, int L = 0, int R = -1) {
        if (R == -1) R = n;
        // if の中身要注意！
        if (r <= L || R <= l) return e1;
        if (l <= L && R <= r) return get(k);
        eval(k);
        int M = (L + R) / 2;
        return f(query(l, r, 2 * k, L, M), query(l, r, 2 * k + 1, M, R));
    }

    T operator[](int i) { return query(i, i + 1); }

    // comp(query[l,r)) = true となるような最大の r (存在しなければ -1)
    template <typename C>
    int find_last(int r, C comp, T &x, int k = 1, int L = 0, int R = -1) {
        if (R == -1) R = n;
        if (r <= L) return -1;
        if (R <= r) {
            if (!comp(f(get(k), x))) {
                x = f(get(k), x);
                return -1;
            }
            if (R - L == 1) return L;
        }
        eval(k);
        int M = (L + R) / 2;
        int l = find_last(r, comp, x, 2 * k + 1, M, R);
        return (l == -1 ? find_last(r, comp, x, 2 * k, L, M) : l);
    }

    template <typename C>
    int find_last(int r, C comp) {
        T x = e1;
        return find_last(r, comp, x);
    }
};

int main() {
    int n, q;
    cin >> n >> q;
    string s;
    cin >> s;
    auto add = [](int a, int b){return a + b;};
    LazySegmentTree<int, int> seg(n, 0, [](int a, int b){return min(a, b);}, add, add, 1e9, 0);
    rep(i, n) seg.update(i, n, s[i] == '(' ? 1 : -1);
    set<int> sl, sr;
    rep(i, n) (s[i] == '(' ? sl : sr).insert(i);
    auto upd = [&](int i) {
        bool f = s[i] == '(';
        (f ? sl : sr).erase(i);
        (f ? sr : sl).insert(i);
        seg.update(i, n, f ? -2 : 2);
        s[i] = f ? ')' : '(';
    };
    while (q--) {
        int x;
        cin >> x;
        x--;
        bool f = s[x] == '(';
        upd(x);
        int idx;
        if (f)
            idx = *begin(sr);
        else {
            int bo = seg.find_last(n, [](int x){return x < 2;});
            idx = *sl.upper_bound(bo);
        }
        cout << idx + 1 << '\n';
        upd(idx);
    }
}
accuracy: 1
time_ms: 600
memory_kb: 25592
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;

template<class T>
bool chmin(T &a, const T &b) {if (a > b) {a = b; return 1;} return 0;}

using ll = long long;
using ld = long double;

bool is_end = false;

/*
SegmentTree(n, f, M1) : n はサイズ、f はマージする二項演算子、M1 はモノイドの単位元
seg(k, x) : k 番目の要素に x を代入
build() : セグメント木を構築
query(a, b) : 区間 [a, b) に対する結果を返す
update(k, x) : k 番目の要素を x に変更し、木の更新も行う
operator[k] : k 番目の要素を返す
find_first(a, check) : 区間 [a, x) が check を満たす最初の要素位置 x を返す
find_last(b, check) : 区間 [x, b) が check を満たす最後の要素位置 x を返す
	- check の型は Function< bool(Monoid) > : query(a, x) の値を引数にとり、bool 値を返す関数
*/

ll f(ll a, ll b) {return min(a, b);}
ll g(ll x, ll f) {return x + f;}
ll h(ll f, ll g) {return f + g;}

template< typename Monoid, typename OperatorMonoid = Monoid >
struct LazySegmentTree {
	using F = function< Monoid(Monoid, Monoid) >;
	using G = function< Monoid(Monoid, OperatorMonoid) >;
	using H = function< OperatorMonoid(OperatorMonoid, OperatorMonoid) >;

	int sz, height;
	vector< Monoid > data;
	vector< OperatorMonoid > lazy;
	const F f;
	const G g;
	const H h;
	const Monoid M1;
	const OperatorMonoid OM0;


	LazySegmentTree(int n, const F f, const G g, const H h,
					const Monoid &M1, const OperatorMonoid OM0)
			: f(f), g(g), h(h), M1(M1), OM0(OM0) {
		sz = 1;
		height = 0;
		while(sz < n) sz <<= 1, height++;
		data.assign(2 * sz, M1);
		lazy.assign(2 * sz, OM0);
	}

	void set(int k, const Monoid &x) {
		data[k + sz] = x;
	}

	void build() {
		for(int k = sz - 1; k > 0; k--) {
			data[k] = f(data[2 * k + 0], data[2 * k + 1]);
		}
	}

	inline void propagate(int k) {
		if(lazy[k] != OM0) {
			lazy[2 * k + 0] = h(lazy[2 * k + 0], lazy[k]);
			lazy[2 * k + 1] = h(lazy[2 * k + 1], lazy[k]);
			data[k] = reflect(k);
			lazy[k] = OM0;
		}
	}

	inline Monoid reflect(int k) {
		return lazy[k] == OM0 ? data[k] : g(data[k], lazy[k]);
	}

	inline void recalc(int k) {
		while(k >>= 1) data[k] = f(reflect(2 * k + 0), reflect(2 * k + 1));
	}

	inline void thrust(int k) {
		for(int i = height; i > 0; i--) propagate(k >> i);
	}

	void update(int a, int b, const OperatorMonoid &x) {
		thrust(a += sz);
		thrust(b += sz - 1);
		for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
			if(l & 1) lazy[l] = h(lazy[l], x), ++l;
			if(r & 1) --r, lazy[r] = h(lazy[r], x);
		}
		recalc(a);
		recalc(b);
	}

	Monoid query(int a, int b) {
		thrust(a += sz);
		thrust(b += sz - 1);
		Monoid L = M1, R = M1;
		for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
			if(l & 1) L = f(L, reflect(l++));
			if(r & 1) R = f(reflect(--r), R);
		}
		return f(L, R);
	}
	
	Monoid operator[](const int &k) {
		return query(k, k + 1);
	}
};

void calc()
{
	ll N, Q; cin >> N >> Q;
	string S; cin >> S;
	
	const ll INF = 1e9;
	LazySegmentTree<ll, ll> seg(N, f, g, h, INF, 0LL);
	ll sum = 0;
	set<int> open, close;
	for (int i = 0; i < N; ++i)
	{
		if (S[i] == '(')
		{
			sum++;
			open.insert(i);
		}
		else
		{
			sum--;
			close.insert(i);
		}
		seg.set(i, sum);
	}
	seg.build();

	while (Q--)
	{
		ll q; cin >> q;
		q--;
		ll res = -1;
		
		if (S[q] == '(')
		{
			open.erase(q);
			seg.update(q, N, -2);
			S[q] = ')';
			close.insert(q);
			
			auto itr = close.begin();
			ll mn = *itr;
			res = mn + 1;
			close.erase(itr);
			S[mn] = '(';
			seg.update(mn, N, +2);
			open.insert(mn);
		}
		else
		{
			close.erase(q);
			seg.update(q, N, +2);
			S[q] = '(';
			open.insert(q);
			
			ll ok = N, ng = 0;
			while (abs(ok - ng) > 1)
			{
				ll mid = (ok + ng) / 2;
				if (seg.query(mid, N) >= 2) {ok = mid;}
				else {ng = mid;}
			}
			
			res = ok + 1;
			open.erase(ok);
			S[ok] = ')';
			seg.update(ok, N, -2);
			close.insert(ok);
		}
		
		cout << res << endl;
	}
	
	return;	
}

int main()
{
	calc();
	
	return 0;
}
accuracy: 1
time_ms: 880
memory_kb: 33828
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep(i, n) for (int i = 0; i < (n); i++)
#define per(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep2(i, l, r) for (int i = (l); i < (r)-1; i++)
#define per2(i, l, r) for (int i = (r)-1; i >= (l); i--)
#define each(e, x) for (auto &e : x)
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define eb emplace_back
#define MM << ' ' <<
#define TT template <typename T>
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

TT bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }
TT bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }

const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;

struct Lazy_Segment_Tree {
    vector<int> data;
    vector<int> lazy;
    int n;

    int f(int a, int b) { return min(a, b); }
    int g(int a, int b) { return a + b; }
    int h(int a, int b) { return a + b; }

    int e1 = inf;
    int e2 = 0;

    Lazy_Segment_Tree(int m) {
        n = 1;
        while (n < m) n <<= 1;
        data.assign(2 * n, 0), lazy.assign(2 * n, 0);
    }

    int get(int k) { return g(data[k], lazy[k]); }

    void eval(int k) {
        data[k] = get(k);
        rep(i, 2) lazy[2 * k + i] = h(lazy[2 * k + i], lazy[k]);
        lazy[k] = e2;
    }

    int apply(int l, int r, int x, int k = 1, int L = 0, int R = -1) {
        if (R == -1) R = n;
        if (l >= r || r <= L || R <= l) return get(k);
        if (l <= L && R <= r) {
            lazy[k] = h(lazy[k], x);
            return get(k);
        }
        eval(k);
        int M = (L + R) / 2;
        return data[k] = f(apply(l, r, x, 2 * k, L, M), apply(l, r, x, 2 * k + 1, M, R));
    }

    int query(int l, int r, int k = 1, int L = 0, int R = -1) {
        if (R == -1) R = n;
        if (l >= r || r <= L || R <= l) return e1;
        if (l <= L && R <= r) return get(k);
        eval(k);
        int M = (L + R) / 2;
        return f(query(l, r, 2 * k, L, M), query(l, r, 2 * k + 1, M, R));
    }
};

int main() {
    int N, Q;
    cin >> N >> Q;

    string S;
    cin >> S;

    vector<int> a(N);
    rep(i, N) a[i] = (S[i] == '(' ? 1 : -1);

    Lazy_Segment_Tree seg(N + 1);
    rep(i, N) seg.apply(i + 1, N + 1, a[i]);

    set<int> s;
    rep(i, N) {
        if (a[i] == -1) s.emplace(i);
    }

    // rep(i, N + 1) cout << seg.query(i, i + 1) << endl;

    auto change = [&](int i) {
        if (a[i] == 1) {
            seg.apply(i + 1, N + 1, -2);
            s.emplace(i);
            a[i] = -1;
        } else {
            seg.apply(i + 1, N + 1, 2);
            s.erase(i);
            a[i] = 1;
        }
    };

    auto query = [&](int i) {
        if (a[i] == 1) {
            change(i);
            int j = *begin(s);
            change(j);
            return j;
        } else {
            change(i);
            int ok = N, ng = -1;
            while (ok - ng > 1) {
                int mid = (ok + ng) / 2;
                if (seg.query(mid, N + 1) >= 2) {
                    ok = mid;
                } else {
                    ng = mid;
                }
            }
            // cout << ng MM ok << endl;
            assert(ng >= 0);
            change(ng);
            return ng;
        }
        return -inf;
    };

    while (Q--) {
        int x;
        cin >> x;
        x--;
        cout << query(x) + 1 << endl;
    }
}
accuracy: 1
time_ms: 970
memory_kb: 19772
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#include <iostream>
using namespace std;
#include <stack>
#include <vector>
#include <set>
#include <queue>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <map>
typedef long long int ll;
typedef long double ld;
#define MAX 300100
#define all(x) (x).begin(), (x).end()
#define pii pair<int, int>
#define inf 1000000000000000
#define _inf -1000000000000000
#define pll pair<ll,ll>
#define pyes cout << "Yes" << '\n'
#define pno cout << "No" << '\n'
#define inv(a) for (int& x: a) cin >> x;
#define llv(a) for (ll& x: a) cin >> x;
#define pri(a) for (int& x: a) cout << x << " "
const int MOD = 1000000007;
// ll dp[MAX][2];
vector<int> g[MAX];
// ll n, m, k;
int n, m, k;
int dau1[4*MAX], dau2[4*MAX], lazy[4*MAX];
int sum[MAX] = {0};

void mix(int id){
    dau1[id] = max(dau1[id*2], dau1[id*2 + 1]);
    dau2[id] = min(dau2[id*2], dau2[id*2 + 1]);
}
void build(int id, int l, int r){
    if (l == r){
        dau1[id] = dau2[id] = sum[l];
        lazy[id] = 0;
        return;
    }
    int mid = (l + r)/2;
    build(id*2, l, mid);
    build(id*2 + 1, mid + 1, r);
    mix(id);
    return;
}


void down(int id){
    if (lazy[id] != 0){
        dau1[id*2] += lazy[id], dau1[id*2 + 1] += lazy[id], lazy[id *2] += lazy[id];
        dau2[id*2] += lazy[id], dau2[id*2 + 1] += lazy[id], lazy[id *2 + 1] += lazy[id];
        lazy[id] = 0;
    }
}
void update(int id, int l, int r, int u, int v, int val){
    if (l > r || l > v || u > r)
        return;
    if (u <= l && r <= v){
        dau1[id] += val;
        dau2[id] += val;
        lazy[id] += val;
        return;
    }
    down(id);
    int mid = (l + r)/2;
        update(id*2, l, mid, u, v, val);
        update(id*2 + 1, mid + 1, r, u, v, val);
    mix(id);
    return;
}

int query1(int id, int l, int r){
    // down(id);
    if (l == r)
        return l;
    down(id);
    int mid = (l + r)/2;
    if (dau1[id*2] != mid){
        return query1(id*2, l, mid);
    }
    else return query1(id*2 + 1, mid + 1, r);
}

int query2(int id, int l, int r){
    
    if (l == r)
        return l;
    down(id);
    int mid = (l + r)/2;
    if (dau2[id*2 + 1] >= 2)    
        return query2(id*2, l, mid);
    else return query2(id*2 + 1, mid + 1, r);
}
void solve(){
    cin >> n >> m;
    string s;
    cin >> s;
    s = "&" + s;
    for (int i = 1; i<=n; i++)
        if (s[i] == '('){
            sum[i] = sum[i - 1] + 1;
        }
        else sum[i] = sum[i - 1] - 1;
    
    build(1, 1, n);
    // for (int i = 1; i<=4*n; i++)
    //     cout << dau1[i] << " ";
    // cout << endl;
    // for (int i = 1; i<=4*n; i++)
    //     cout << dau2[i] << " ";
    // cout << endl;
    while (m--){
        int x;
        cin >> x;
        if (s[x] == '('){
            update(1, 1, n, x, n, -2);
            s[x] = ')';
            int tmp = query1(1, 1, n);
            s[tmp] = '(';
            update(1, 1, n, tmp, n, 2);
            cout << tmp << endl;
        }
        else{
            update(1, 1, n, x, n, 2);
            s[x] = '(';
            int tmp = query2(1, 1, n) + 1;
            s[tmp] = ')';
            update(1, 1, n, tmp, n, -2);
            cout << tmp << endl;
        }
    }
} 



int main() {
    int t;
    t = 1;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    // cin >> t;
    while (t--)
        solve();
    return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 25924
final_rank: 5

code_snippet: #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

const int BACKET = 500;

class DataStructure {
	public:
	int size_ = 0;
	vector<int> Addi;
	vector<int> Minv;
	vector<int> Array;
	
	void init(int sz) {
		size_ = (sz + BACKET - 1) / BACKET;
		Addi.resize(size_, 0);
		Minv.resize(size_, 0);
		Array.resize(size_ * BACKET, 0);
	}
	
	// Add x after pos
	void add(int pos, int x) {
		int idx = pos / BACKET;
		for (int i = pos; i < (idx + 1) * BACKET; i++) Array[i] += x;
		Minv[idx] = (1<<30);
		for (int i = idx * BACKET; i < (idx + 1) * BACKET; i++) Minv[idx] = min(Minv[idx], Array[i]);
		for (int i = idx + 1; i < size_; i++) Addi[i] += x;
	}
	
	// Get place where min(A[i], ..., A[size_-1]) >= 2
	int getans() {
		for (int i = size_ - 1; i >= 0; i--) {
			if (Addi[i] + Minv[i] >= 2) continue;
			for (int j = BACKET - 1; j >= 0; j--) {
				if (Addi[i] + Array[i * BACKET + j] >= 2) continue;
				return i * BACKET + j + 1;
			}
		}
		return 0;
	}
};

int N, Q, X[150009];
string S;
set<int> S0, S1;
DataStructure Z;

void Change(int pos, char c) {
	if (c == ')') {
		S[pos] = c;
		Z.add(pos + 1, -2);
		S0.erase(pos); S1.insert(pos);
	}
	else {
		S[pos] = c;
		Z.add(pos + 1, 2);
		S1.erase(pos); S0.insert(pos);
	}
}

int main() {
	// Input
	cin >> N >> Q;
	cin >> S;
	for (int i = 1; i <= Q; i++) cin >> X[i];
	for (int i = 1; i <= Q; i++) X[i] -= 1;
	
	// Prepare
	Z.init(N + 2);
	for (int i = 0; i < N; i++) {
		if (S[i] == '(') { S0.insert(i); Z.add(i + 1, 1); }
		if (S[i] == ')') { S1.insert(i); Z.add(i + 1, -1); }
	}
	
	// Answer Query
	for (int i = 1; i <= Q; i++) {
		if (S[X[i]] == '(') {
			Change(X[i], ')');
			auto itr = S1.begin();
			int pos = (*itr);
			cout << pos + 1 << endl;
			Change(pos, '(');
		}
		else {
			Change(X[i], '(');
			int pos = Z.getans(); pos -= 1;
			cout << pos + 1 << endl;
			Change(pos, ')');
		}
	}
	return 0;
}
accuracy: 1
time_ms: 650
memory_kb: 19216
final_rank: 4

code_snippet: #include "bits/stdc++.h"

using namespace std;

constexpr long long MOD=998244353;

class Segment_Tree {
	vector<long long int>v;
	vector<long long int>add;
	vector<long long int>modi;
	vector<int>l;
	vector<int>r;
	int num;
	long long int ret;
	bool is_min;
	void Left(int place) {
		if (place >= v.size() / 2) {
			l[place] = place - v.size() / 2;
			return;
		}
		Left(place * 2);
		Left(place * 2 + 1);
		l[place] = l[place * 2];
		return;
	}
	void Right(int place) {
		if (place >= v.size() / 2) {
			r[place] = place - v.size() / 2;
			return;
		}
		Right(place * 2);
		Right(place * 2 + 1);
		r[place] = r[place * 2 + 1];
		return;
	}
	long long int Update(int place) {
		if (place >= v.size() / 2) {
			return v[place];
		}
		if (is_min) {
			v[place] = min(Update(place * 2), Update(place * 2 + 1));
			return v[place];
		}
		v[place] = max(Update(place * 2), Update(place * 2 + 1));
		return v[place];
	}
	void Modify(int a, int b, long long int num, int place) {
		if (l[place] >= a && r[place] <= b) {
			modi[place] = num;
			v[place] = num;
			add[place] = 0;
			return;
		}
		if (l[place] > b || r[place] < a)return;
		if (modi[place] != LLONG_MAX) {
			modi[place * 2] = modi[place * 2 + 1] = modi[place];
			v[place * 2] = v[place * 2 + 1] = modi[place];
			add[place * 2] = add[place * 2 + 1] = 0;
			modi[place] = LLONG_MAX;
		}
		add[place * 2] += add[place];
		add[place * 2 + 1] += add[place];
		add[place] = 0;
		Modify(a, b, num, place * 2);
		Modify(a, b, num, place * 2 + 1);
		if (is_min)v[place] = min(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		else v[place] = max(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		return;
	}
	void Add(int a, int b, long long int num, int place) {
		if (l[place] >= a && r[place] <= b) {
			if (modi[place] != LLONG_MAX) {
				if (place * 2 < v.size()) {
					modi[place * 2] = modi[place * 2 + 1] = modi[place];
					v[place * 2] = v[place * 2 + 1] = modi[place];
					add[place * 2] = add[place * 2 + 1] = 0;
				}
				modi[place] = LLONG_MAX;
			}
			add[place] += num;
			return;
		}
		if (l[place] > b || r[place] < a)return;
		if (modi[place] != LLONG_MAX) {
			modi[place * 2] = modi[place * 2 + 1] = modi[place];
			v[place * 2] = v[place * 2 + 1] = modi[place];
			add[place * 2] = add[place * 2 + 1] = 0;
			modi[place] = LLONG_MAX;
		}
		add[place * 2] += add[place];
		add[place * 2 + 1] += add[place];
		add[place] = 0;
		Add(a, b, num, place * 2);
		Add(a, b, num, place * 2 + 1);
		if (is_min)v[place] = min(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		else v[place] = max(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		return;
	}
	void RMQ(int a, int b, int place) {
		if (l[place] >= a && r[place] <= b) {
			if (modi[place] != LLONG_MAX) {
				if (place * 2 < v.size()) {
					modi[place * 2] = modi[place * 2 + 1] = modi[place];
					v[place * 2] = v[place * 2 + 1] = modi[place];
					add[place * 2] = add[place * 2 + 1] = 0;
				}
				modi[place] = LLONG_MAX;
			}
			if (is_min)ret = min(ret, v[place] + add[place]);
			else ret = max(ret, v[place] + add[place]);
			return;
		}
		if (l[place] > b || r[place] < a) return;
		if (modi[place] != LLONG_MAX) {
			modi[place * 2] = modi[place * 2 + 1] = modi[place];
			v[place * 2] = v[place * 2 + 1] = modi[place];
			add[place * 2] = add[place * 2 + 1] = 0;
			modi[place] = LLONG_MAX;
		}
		add[place * 2] += add[place];
		add[place * 2 + 1] += add[place];
		add[place] = 0;
		RMQ(a, b, place * 2);
		RMQ(a, b, place * 2 + 1);
		if (is_min)v[place] = min(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		else v[place] = max(v[place * 2] + add[place * 2], v[place * 2 + 1] + add[place * 2 + 1]);
		return;
	}
public:
	Segment_Tree(int n, bool min) {
		n++;
		num = 1;
		while (num < n * 2) {
			num *= 2;
		}
		l.resize(num);
		r.resize(num);
		is_min = min;
		if (min) {
			v.resize(num, MOD * MOD);
		}
		else v.resize(num, -MOD * MOD);
		add.resize(num, 0);
		modi.resize(num, LLONG_MAX);
		Left(1);
		Right(1);
	}
	void Insert(int place, long long int num, bool update) {
		place += v.size() / 2;
		v[place] = num;
		if (!update)return;
		place /= 2;
		while (place) {
			if (is_min)v[place] = min(v[place * 2], v[place * 2 + 1]);
			else v[place] = max(v[place * 2], v[place * 2 + 1]);
			place /= 2;
		}
	}
	void Modify(int a, int b, long long int num) {
		Modify(a, b, num, 1);
	}
	void Add(int a, int b, long long int num) {
		Add(a, b, num, 1);
	}
	void Init() {
		Update(1);
	}
	long long int RMQ(int a, int b) {
		if (is_min)ret = LLONG_MAX;
		else ret = LLONG_MIN;
		RMQ(a, b, 1);
		return ret;
	}
};

int main(){
    int N,K;
    cin>>N>>K;
    string s;
    cin>>s;
    Segment_Tree mn(N,true);
    set<int>st;
    int num=0;
    for(int i=0;i<N;i++){
        if(s[i]=='(')num++;
        else {
            num--;
            st.insert(i);
        }
        mn.Modify(i,i,num);
    }
    while(K--){
        int p;
        cin>>p;
        p--;
        s[p]^='('^')';
        if(s[p]=='('){
            st.erase(p);
            mn.Add(p,N-1,2);
            int l=-0,r=N;
            while(r-l>1){
                int mid=(l+r)/2;
                if(mn.RMQ(mid,N)>=2)r=mid;
                else l=mid;
            }
            cout<<r+1<<endl;
            s[r]^='('^')';
            st.insert(r);
            mn.Add(r,N-1,-2);
        }
        else{
            st.insert(p);
            mn.Add(p,N-1,-2);
            int r=*st.begin();
            s[r]^='('^')';
            st.erase(r);
            cout<<r+1<<endl;
            mn.Add(r,N-1,2);
        }
    }
}
accuracy: 1
time_ms: 1280
memory_kb: 43276
final_rank: 20

code_snippet: #include <bits/stdc++.h>

using namespace std;
#define ll long long
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define rep2(i, a, b) for(ll i = (a); i < (b); i++)
#define vi vector<int>
#define si(c) (c).size()

template <typename T, typename F> struct segtree {
    int n;
    vector<T> seg;
    F f;
    T id;
    segtree() = default;
    segtree(int nn, F f, T id) : f(f), id(id) {
        n = 1;
        while(n < nn) n <<= 1;
        seg.assign(n * 2, id);
    }
    void set(int i, T x) { seg[i + n] = x; }
    void build() {
        for(int k = n - 1; k > 0; k--) { seg[k] = f(seg[2 * k], seg[2 * k + 1]); }
    }
    void update(int i, T x) {
        set(i, x);
        i += n;
        while(i >>= 1) seg[i] = f(seg[i * 2], seg[i * 2 + 1]);
    }
    T get(int i) { return seg[i + n]; }
    T prod(int l, int r) {
        T L = id, R = id;
        for(l += n, r += n; l < r; l >>= 1, r >>= 1) {
            if(l & 1) L = f(L, seg[l++]);
            if(r & 1) R = f(seg[--r], R);
        }
        return f(L, R);
    }
};

int main() {
    int n, q;
    cin >> n >> q;
    string s;
    cin >> s;
    vi v(n);
    rep(i, n) v[i] = (s[i] == '(');

    struct S {
        int now, mi;
    };
    auto f = [](S l, S r) { return S{l.now + r.now, min(l.now + r.mi, l.mi)}; };
    segtree<S, decltype(f)> seg(n, f, S{0, (int)1e9});
    rep(i, n) seg.set(i, (v[i] ? S{1, 1} : S{-1, -1}));
    seg.build();

    set<int> l, r;
    rep(i, n)(v[i] ? l : r).emplace(i);
    // cout << *l.lower_bound(1) << endl;

    auto ch = [&](int i) {
        if(v[i]) {
            v[i] = 0;
            l.erase(i);
            r.emplace(i);
            seg.update(i, S{-1, -1});
        } else {
            v[i] = 1;
            l.emplace(i);
            r.erase(i);
            seg.update(i, S{1, 1});
        }
    };

    // cout << seg.prod(1, 3).mi << endl;
    rep(_, q) {
        int x;
        cin >> x;
        x--;
        ch(x);
        if(!v[x]) {
            cout << *begin(r) + 1 << endl;
            ch(*begin(r));
        } else {
            int ok = x, ng = 0;
            while(ng < ok - 1) {
                int mid = ok + ng >> 1;
                int nxt = *l.lower_bound(mid);
                ch(nxt);
                (seg.seg[1].mi >= 0 ? ok : ng) = mid;
                ch(nxt);
            }
            ok = *l.lower_bound(ok);
            cout << ok + 1 << endl;
            ch(ok);
        }

        // rep(i, n) cout << ")("[v[i]];
        // cout << endl;
    }
}
accuracy: 1
time_ms: 1980
memory_kb: 26852
final_rank: 19

code_snippet: #include <bits/stdc++.h>

using namespace std;
#define ll long long
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define rep2(i, a, b) for(ll i = (a); i < (b); i++)
#define vi vector<int>
#define si(c) (c).size()

template <typename T, typename F> struct segtree {
    int n;
    vector<T> seg;
    F f;
    T id;
    segtree() = default;
    segtree(int nn, F f, T id) : f(f), id(id) {
        n = 1;
        while(n < nn) n <<= 1;
        seg.assign(n * 2, id);
    }
    void set(int i, T x) { seg[i + n] = x; }
    void build() {
        for(int k = n - 1; k > 0; k--) { seg[k] = f(seg[2 * k], seg[2 * k + 1]); }
    }
    void update(int i, T x) {
        set(i, x);
        i += n;
        while(i >>= 1) seg[i] = f(seg[i * 2], seg[i * 2 + 1]);
    }
    T get(int i) { return seg[i + n]; }
    T prod(int l, int r) {
        T L = id, R = id;
        for(l += n, r += n; l < r; l >>= 1, r >>= 1) {
            if(l & 1) L = f(L, seg[l++]);
            if(r & 1) R = f(seg[--r], R);
        }
        return f(L, R);
    }
};

int main() {
    int n, q;
    cin >> n >> q;
    string s;
    cin >> s;
    vi v(n);
    rep(i, n) v[i] = (s[i] == '(');

    struct S {
        int now, mi;
    };
    auto f = [](S l, S r) { return S{l.now + r.now, min(l.now + r.mi, l.mi)}; };
    segtree<S, decltype(f)> seg(n, f, S{0, (int)1e9});
    rep(i, n) seg.set(i, (v[i] ? S{1, 1} : S{-1, -1}));
    seg.build();

    set<int> l, r;
    rep(i, n)(v[i] ? l : r).emplace(i);
    // cout << *l.lower_bound(1) << endl;

    auto ch = [&](int i) {
        if(v[i]) {
            v[i] = 0;
            l.erase(i);
            r.emplace(i);
            seg.update(i, S{-1, -1});
        } else {
            v[i] = 1;
            l.emplace(i);
            r.erase(i);
            seg.update(i, S{1, 1});
        }
    };

    // cout << seg.prod(1, 3).mi << endl;
    rep(_, q) {
        int x;
        cin >> x;
        x--;
        ch(x);
        if(!v[x]) {
            cout << *begin(r) + 1 << endl;
            ch(*begin(r));
        } else {
            int ok = x, ng = 0;
            while(ng < ok - 1) {
                int mid = ok + ng >> 1;
                int L = seg.prod(0, mid).now;
                if(L > 0 and seg.prod(mid, x).mi + L > 1)
                    ok = mid;
                else
                    ng = mid;
            }
            ok = *l.lower_bound(ok);
            cout << ok + 1 << endl;
            ch(ok);
        }

        // rep(i, n) cout << ")("[v[i]];
        // cout << endl;
    }
}
accuracy: 1
time_ms: 600
memory_kb: 26844
final_rank: 13

code_snippet: #include <bits/stdc++.h>

using namespace std;

struct segtree {
    using S = int;
    using F = int;

    S e() {
        return 1e9;
    }

    S op(S a, S b) {
        return min(a, b);
    }

    S mapping(F f, S x) {
        x += f;
        return x;
    }

    F composition(F f, F g) {
        return f + g;
    }

    F id() {
        return 0;
    }

    int n, ln;
    vector<S> d;
    vector<F> lz;

    void update(int k) {
        d[k] = op(d[2 * k], d[2 * k + 1]);
    }

    void all_apply(int k, F f) {
        d[k] = mapping(f, d[k]);
        if (k < n) {
            lz[k] = composition(f, lz[k]);
        }
    }

    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = id();
    }

    segtree(int nn) {
        n = 1;
        ln = 0;
        while (n < nn) {
            n <<= 1;
            ln++;
        }
        d = vector<S>(2 * n, e());
        for (int i = 0; i < nn; i++) {
            d[n + i] = 0;
        }
        for (int i = n - 1; i >= 1; i--) {
            update(i);
        }
        lz = vector<F>(n, id());
    }

    S prod(int l, int r) {
        l += n;
        r += n;
        for (int i = ln; i >= 1; i--) {
            if (((l >> i) << i) != l) {
                push(l >> i);
            }
            if (((r >> i) << i) != r) {
                push((r - 1) >> i);
            }
        }
        S sl = e(), sr = e();
        while (l < r) {
            if (l & 1) {
                sl = op(sl, d[l++]);
            }
            if (r & 1) {
                sr = op(d[--r], sr);
            }
            l >>= 1;
            r >>= 1;
        }
        return op(sl, sr);
    }

    void apply(int l, int r, F f) {
        l += n;
        r += n;
        for (int i = ln; i >= 1; i--) {
            if (((l >> i) << i) != l) {
                push(l >> i);
            }
            if (((r >> i) << i) != r) {
                push((r - 1) >> i);
            }
        }
        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) {
                    all_apply(l++, f);
                }
                if (r & 1) {
                    all_apply(--r, f);
                }
                l >>= 1;
                r >>= 1;
            }
            l = l2, r = r2;
        }
        for (int i = 1; i <= ln; i++) {
            if (((l >> i) << i) != l) {
                update(l >> i);
            }
            if (((r >> i) << i) != r) {
                update((r - 1) >> i);
            }
        }
    }

};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, q;
    cin >> n >> q;
    string s;
    cin >> s;
    segtree seg(n);
    for (int i = 0; i < n; i++) {
        if (s[i] == '(') {
            seg.apply(0, i + 1, -1);
        } else {
            seg.apply(0, i + 1, +1);
        }
    }
    set<int> st;
    for (int i = 0; i < n; i++) {
        if (s[i] == ')') {
            st.emplace(i);
        }
    }
    auto Flip = [&](int i) {
        if (s[i] == '(') {
            st.emplace(i);
            seg.apply(0, i + 1, +2);
            s[i] = ')';
        } else {
            st.erase(i);
            seg.apply(0, i + 1, -2);
            s[i] = '(';
        }
    };
    while (q--) {
        int x;
        cin >> x;
        x--;
        int y = -1;
        if (s[x] == '(') {
            Flip(x);
            y = *st.begin();
        } else {
            Flip(x);
            int low = 0, high = n;
            while (high - low > 1) {
                int mid = (high + low) >> 1;
                auto p = seg.prod(mid, n);
                if (p < 0) {
                    low = mid;
                } else {
                    high = mid;
                }
            }
            // cerr << seg.prod(0, n) << endl;
            y = low;
        }
        cout << y + 1 << '\n';
        Flip(y);
    }
    return 0;
}
accuracy: 1
time_ms: 480
memory_kb: 16480
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

template <typename M, typename O, typename M::T (*act)(typename M::T, typename O::T)>
class LazySegmentTree {
    using T = typename M::T;
    using E = typename O::T;

public:
    LazySegmentTree() = default;
    explicit LazySegmentTree(int n) : LazySegmentTree(std::vector<T>(n, M::id())) {}
    explicit LazySegmentTree(const std::vector<T>& v) {
        size = 1;
        while (size < (int) v.size()) size <<= 1;
        node.resize(2 * size, M::id());
        lazy.resize(2 * size, O::id());
        std::copy(v.begin(), v.end(), node.begin() + size);
        for (int i = size - 1; i > 0; --i) node[i] = M::op(node[2 * i], node[2 * i + 1]);
    }

    T operator[](int k) {
        return fold(k, k + 1);
    }

    void update(int l, int r, const E& x) { update(l, r, x, 1, 0, size); }

    T fold(int l, int r) { return fold(l, r, 1, 0, size); }

private:
    int size;
    std::vector<T> node;
    std::vector<E> lazy;

    void push(int k) {
        if (lazy[k] == O::id()) return;
        if (k < size) {
            lazy[2 * k] = O::op(lazy[2 * k], lazy[k]);
            lazy[2 * k + 1] = O::op(lazy[2 * k + 1], lazy[k]);
        }
        node[k] = act(node[k], lazy[k]);
        lazy[k] = O::id();
    }

    void update(int a, int b, const E& x, int k, int l, int r) {
        push(k);
        if (r <= a || b <= l) return;
        if (a <= l && r <= b) {
            lazy[k] = O::op(lazy[k], x);
            push(k);
            return;
        }
        int m = (l + r) / 2;
        update(a, b, x, 2 * k, l, m);
        update(a, b, x, 2 * k + 1, m, r);
        node[k] = M::op(node[2 * k], node[2 * k + 1]);
    }

    T fold(int a, int b, int k, int l, int r) {
        push(k);
        if (r <= a || b <= l) return M::id();
        if (a <= l && r <= b) return node[k];
        int m = (l + r) / 2;
        return M::op(fold(a, b, 2 * k, l, m),
                     fold(a, b, 2 * k + 1, m, r));
    }
};

struct MinMonoid {
    using T = int;
    static T id() { return (1u << 31) - 1; }
    static T op(T a, T b) {
        return min(a, b);
    }
};

struct AddMonoid {
    using T = int;
    static T id() { return 0; }
    static T op(T a, T b) {
        return a + b;
    }
};

int act(int x, int a) {
    return x + a;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    int N, Q;
    cin >> N >> Q;
    string s;
    cin >> s;

    vector<int> zeros(N+1);
    LazySegmentTree<MinMonoid, AddMonoid, act> st(zeros);
    set<int> close;

    rep(i,0,N) {
        st.update(i+1, N+1, s[i] == '(' ? 1 : -1);
        if (s[i] == ')') close.insert(i);
    }

    while (Q--) {
        int q;
        cin >> q;
        --q;
        if (s[q] == '(') {
            s[q] = ')';
            close.insert(q);
            st.update(q+1, N+1, -2);
            // flip the leftmost )
            auto it = close.begin();
            int i = *it;
            s[i] = '(';
            st.update(i+1, N+1, 2);
            close.erase(it);
            cout << i+1 << "\n";
        } else {
            s[q] = '(';
            close.erase(q);
            st.update(q+1, N+1, 2);
            // flip the leftmost ( s.t. min(i+1,...,N+1) == 2
            int lb = 0, ub = N;
            while (ub - lb > 1) {
                int m = (lb + ub) / 2;
                if (st.fold(m, N+1) >= 2) {
                    ub = m;
                } else {
                    lb = m;
                }
            }
            s[lb] = ')';
            st.update(lb+1, N+1, -2);
            close.insert(lb);
            cout << lb+1 << "\n";
        }
    }
}
accuracy: 1
time_ms: 750
memory_kb: 19848
final_rank: 7

code_snippet: #line 1 "c.cpp"
/*	author:  Kite_kuma
	created: 2022.03.03 13:47:42 */

// #ifdef LOCAL
// #define _GLIBCXX_DEBUG
// #endif
#include <bits/stdc++.h>
using namespace std;

#pragma region macros

#define foa(s, v) for(auto &s : v)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define popcnt(n) __builtin_popcountll((long long)n)

#define REPname(a, b, c, d, e, ...) e
#define rep(...) REPname(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define REP0(x) for(int Counter_in_rep_macro = 0; Counter_in_rep_macro < (x); ++Counter_in_rep_macro)
#define REP1(i, x) for(int i = 0; i < (x); ++i)
#define REP2(i, l, r) for(int i = (l); i < (r); ++i)
#define REP3(i, l, r, c) for(int i = (l); i < (r); i += (c))

#define DREPname(a, b, c, d, e, ...) e
#define drep(...) DREPname(__VA_ARGS__, DREP3, DREP2, DREP1)(__VA_ARGS__)
#define DREP1(i, x) for(int i = (x)-1; i >= 0; --i)
#define DREP2(i, l, r) for(int i = (r)-1; i >= (l); --i)
#define DREP3(i, l, r, c) for(int i = (r)-1; i >= (l); i -= (c))

#pragma endregion

#pragma region aliases

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = std::vector<int>;
using vvi = std::vector<std::vector<int>>;
using vvvi = std::vector<std::vector<std::vector<int>>>;
using vll = std::vector<ll>;
using vvll = std::vector<vll>;
using vvvll = std::vector<vvll>;
using pii = std::pair<int, int>;
using pll = std::pair<long long, long long>;
template <class T = ll>
using V = std::vector<T>;
template <class T = ll>
using VV = V<V<T>>;
template <class T = ll>
using VVV = V<V<V<T>>>;
template <class T = ll>
using pqup = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <class T = ll>
using pqdn = std::priority_queue<T>;

#pragma endregion

#pragma region constants

const int inf = 1e9;
const long long INF = 1e18;
const long double pi = acos(-1);
const char dl = '\n';
const char sp = ' ';
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

const int mod_1000000007 = 1000000007;
const int mod_998244353 = 998244353;

#pragma endregion

#pragma region basic_operation

template <class T0, class T1, class T2>
inline bool in_range(T0 x, T1 lef, T2 rig) {
	return ((lef <= x) && (x < rig));
}

template <class T>
inline bool chmin(T &a, T b) {
	if(a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmax(T &a, T b) {
	if(a < b) {
		a = b;
		return true;
	}
	return false;
}

void Yes(bool f = 1) { std::cout << (f ? "Yes" : "No") << '\n'; }
void No() { std::cout << "No\n"; }
void YES(bool f = 1) { std::cout << (f ? "YES" : "NO") << '\n'; }
void NO() { std::cout << "NO\n"; }

template <class T>
void drop(T answer) {
	std::cout << answer << '\n';
	exit(0);
}

void err(bool flag = true) {
	if(!flag) return;
	std::cout << -1 << '\n';
	exit(0);
}

template <class T>
void vout(std::vector<T> const &v, bool vertically = 0) {
	if(vertically) {
		for(auto const &a : v) {
			std::cout << a << '\n';
		}
		return;
	}
	for(auto it = v.begin(); it != v.end(); it++) {
		std::cout << (*it);
		if(it != v.end() - 1) {
			std::cout << ' ';
		}
	}
	std::cout << '\n';
	return;
}

inline void print() { std::cout << '\n'; }
template <class T>
inline void print(T x) {
	std::cout << x << '\n';
	return;
}
template <typename Head, typename... Tail>
void print(Head H, Tail... T) {
	std::cout << H << " ";
	print(T...);
}

template <class T>
void add(std::vector<T> &v, T val) {
	for(auto &a : v) a += val;
	return;
}

template <class T>
T dup(T a, T b) {
	assert(b != 0);
	return (a + b - 1) / b;
}

template <class T>
T greatest_lower_multiple(T x, T d) {
	if(d == 0) return 0;
	if(d < 0) d *= -1;
	T y = x % d;
	if(y < 0) y += d;
	return x - y;
}

template <class T>
T least_upper_multiple(T x, T d) {
	return -greatest_lower_multiple(-x, d);
}

long long POW(long long a, long long n) {
	long long res = 1;
	while(n > 0) {
		if(n & 1) res = res * a;
		a = a * a;
		n >>= 1;
	}
	return res;
}

long long modpow(long long a, long long n, long long mod) {	 // a^n mod
	assert(n >= 0 && mod);
	if(mod == 1) return 0LL;
	long long res = 1;
	a %= mod;
	while(n > 0) {
		if(n & 1) res = res * a % mod;
		a = a * a % mod;
		n >>= 1;
	}
	return res < 0 ? res + mod : res;
}

// return x which satisfies a * x % mod == gcd(a, mod)
// not (mod | a)
long long modinv(long long a, long long mod) {
	long long b = mod, u = 1, v = 0;
	while(b) {
		long long t = a / b;
		a -= t * b;
		std::swap(a, b);
		u -= t * v;
		std::swap(u, v);
	}
	u %= mod;
	if(u < 0) u += mod;
	return u;
}

template <class T>
int lb(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::lower_bound(a.begin(), a.end(), x));
}
template <class T>
int ub(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::upper_bound(a.begin(), a.end(), x));
}
template <class T>
void unq_sort(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<int> press(std::vector<T> &a) {
	auto vec = a;
	unq_sort(vec);
	std::vector<int> ret;
	for(auto &v : a) ret.push_back(lb(vec, v));
	return ret;
}

#pragma endregion

#pragma region input
#define VEC(type, name, size) \
	vector<type> name(size);  \
	scanner::INPUT(name)
#define VVEC(type, name, h, w)                     \
	vector<vector<type>> name(h, vector<type>(w)); \
	scanner::INPUT(name)
#define INT(...)     \
	int __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
	long long __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define STR(...)        \
	string __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define CHR(...)      \
	char __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define DBL(...)        \
	double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
	long double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define TPL3(type0, type1, type2, name)   \
	std::tuple<type0, type1, type2> name; \
	scanner::INPUT(name);
#define TPL4(type0, type1, type2, type3, name)   \
	std::tuple<type0, type1, type2, type3> name; \
	scanner::INPUT(name);

namespace scanner {
template <class T>
void scan(T &a) {
	std::cin >> a;
}

template <class T, class L>
void scan(std::pair<T, L> &p) {
	scan(p.first);
	scan(p.second);
}

template <class T0, class T1, class T2>
void scan(std::tuple<T0, T1, T2> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	scan(t0);
	scan(t1);
	scan(t2);
	p = std::make_tuple(t0, t1, t2);
}

template <class T0, class T1, class T2, class T3>
void scan(std::tuple<T0, T1, T2, T3> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	T3 t3;
	scan(t0);
	scan(t1);
	scan(t2);
	scan(t3);
	p = std::make_tuple(t0, t1, t2, t3);
}

template <class T>
void scan(std::vector<T> &a) {
	for(auto &i : a) scan(i);
}

void INPUT() {}
template <class Head, class... Tail>
void INPUT(Head &head, Tail &... tail) {
	scan(head);
	INPUT(tail...);
}
}  // namespace scanner

template <typename T1, typename T2>
std::istream &operator>>(std::istream &is, std::pair<T1, T2> &p) {
	is >> p.first >> p.second;
	return is;
}
#pragma endregion

#pragma region debug

#pragma region output
template <typename T1, typename T2>
std::ostream &std::operator<<(std::ostream &os, const std::pair<T1, T2> &p) {
	os << p.first << " " << p.second;
	return os;
}
template <class T>
std::ostream &std::operator<<(std::ostream &os, const std::vector<T> &v) {
	for(int i = 0; i < (int)v.size(); i++) {
		if(i) os << " ";
		os << v[i];
	}
	return os;
}
#pragma endregion

#pragma region view

namespace viewer {
void view(const long long e) {
	if(e == INF)
		std::cerr << "INF";
	else if(e == -INF)
		std::cerr << "-INF";
	else
		std::cerr << e;
}

void view(const int e) {
	if(e == inf)
		std::cerr << "inf";
	else if(e == -inf)
		std::cerr << "-inf";
	else
		std::cerr << e;
}

template <typename T>
void view(const T e) {
	std::cerr << e;
}

template <typename T, typename U>
void view(const std::pair<T, U> &p) {
	std::cerr << "(";
	view(p.first);
	std::cerr << ", ";
	view(p.second);
	std::cerr << ")";
}

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ")";
}

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ", ";
	view(std::get<3>(p));
	std::cerr << ")";
}

template <typename T>
void view(const std::set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::unordered_set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<T> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(const auto &e : v) {
		view(e);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<std::vector<T>> &vv) {
	std::cerr << "{\n";
	for(const auto &v : vv) {
		std::cerr << "\t";
		view(v);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v) {
	std::cerr << "{\n";
	for(const auto &c : v) {
		std::cerr << "\t(";
		view(c.first);
		std::cerr << ", ";
		view(c.second);
		std::cerr << ")\n";
	}
	std::cerr << "}";
}

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <typename T, typename U>
void view(const std::map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}
}  // namespace viewer

#pragma endregion

// when debugging : g++ foo.cpp -DLOCAL
#ifdef LOCAL
void debug_out() {}
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
	viewer::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "\b\b]\n";                                   \
	} while(0)
#define dump(x)                                      \
	do {                                             \
		std::cerr << __LINE__ << " " << #x << " : "; \
		viewer::view(x);                             \
		std::cerr << '\n';                           \
	} while(0)

#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

#pragma endregion

#line 1 "atcoder/lazysegtree.hpp"



#line 8 "atcoder/lazysegtree.hpp"

#line 1 "atcoder/internal_bit.hpp"



#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param n `0 <= n`
// @return minimum non-negative `x` s.t. `n <= 2**x`
int ceil_pow2(int n) {
    int x = 0;
    while ((1U << x) < (unsigned int)(n)) x++;
    return x;
}

// @param n `1 <= n`
// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
constexpr int bsf_constexpr(unsigned int n) {
    int x = 0;
    while (!(n & (1 << x))) x++;
    return x;
}

// @param n `1 <= n`
// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
int bsf(unsigned int n) {
#ifdef _MSC_VER
    unsigned long index;
    _BitScanForward(&index, n);
    return index;
#else
    return __builtin_ctz(n);
#endif
}

}  // namespace internal

}  // namespace atcoder


#line 10 "atcoder/lazysegtree.hpp"

namespace atcoder {

template <class S,
          S (*op)(S, S),
          S (*e)(),
          class F,
          S (*mapping)(F, S),
          F (*composition)(F, F),
          F (*id)()>
struct lazy_segtree {
  public:
    lazy_segtree() : lazy_segtree(0) {}
    explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    explicit lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
        log = internal::ceil_pow2(_n);
        size = 1 << log;
        d = std::vector<S>(2 * size, e());
        lz = std::vector<F>(size, id());
        for (int i = 0; i < _n; i++) d[size + i] = v[i];
        for (int i = size - 1; i >= 1; i--) {
            update(i);
        }
    }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;
    std::vector<F> lz;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f) {
        d[k] = mapping(f, d[k]);
        if (k < size) lz[k] = composition(f, lz[k]);
    }
    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = id();
    }
};

}  // namespace atcoder


#line 553 "c.cpp"

using S = ll;
using F = ll;

S op(S a, S b) { return min(a, b); }
S e() { return INF; }
S mapping(F f, S s) { return s + f; }
F comp(F f, F g) { return f + g; }
F id() { return 0LL; }
bool g(S value) { return value > 1; }
void solve(int n) {
	int q;
	cin >> q;
	string s;
	cin >> s;

	vector<int> prs;
	foa(c, s) prs.push_back(c == '(' ? 1 : -1);

	vll acc = {0};
	foa(c, prs) acc.push_back(c + acc.back());
	atcoder::lazy_segtree<S, op, e, F, mapping, comp, id> lst(acc);

	// using ope = ll;
	// using monoid = pair<ll, int>;  // minvalue, maxidx;

	// auto dot = [&](monoid a, monoid b) {
	// 	if(a.first != b.first) return min(a, b);
	// 	return make_pair(a.first, max(a.second, b.second));
	// };

	// auto func = [&](monoid m, ope f) { return make_pair(f + m.first, m.second); };

	// auto comp = [](ope a, ope b) { return a + b; };

	set<int> rightbrakets, leftbrakets;
	rep(i, n) {
		if(prs[i] == -1)
			rightbrakets.insert(i);
		else
			leftbrakets.insert(i);
	}

	auto flip = [&](int pos) {
		debug(pos);
		int backvalue = 2;
		if(prs[pos] == 1) {
			backvalue = -2;
			assert(!rightbrakets.count(pos));
			rightbrakets.insert(pos);
			leftbrakets.erase(pos);
		} else {
			assert(rightbrakets.count(pos));
			rightbrakets.erase(pos);
			leftbrakets.insert(pos);
		}
		prs[pos] *= -1;
		// lst.update(pos + 1, n + 1, backvalue);
		// assert(lst.get(n, n + 1).second == backvalue);
		lst.apply(pos + 1, int(acc.size()), backvalue);
		return backvalue;
	};

	auto query = [&](int flip_pos) -> int {
		debug(flip_pos, rightbrakets);
		int bv = flip(flip_pos);
		int change;
		debug(flip_pos, bv);
		// #ifdef LOCAL
		// 		rep(i, n + 1) { debug(i, lst.get(i, i + 1)); }
		// #endif
		if(bv == 2) {  // imakara ( -> )
			// monoid res = lst.get(0, n + 1);
			// change = res.second + 1;
			// debug(res);

			int mid = lst.min_left(int(acc.size()), g);
			change = mid-1;
			flip(change);
		} else {
			change = *(rightbrakets.begin());
			flip(change);
		}
		// assert(lst.get(n, n + 1).first == 0LL);
		return change;
	};

	rep(q) {
		int pos;
		cin >> pos;
		cout << query(pos - 1) + 1 << dl;
		assert(rightbrakets.size() == n / 2);
		// #ifdef LOCAL
		// 		assert(!accumulate(all(prs), 0));
		// 		rep(i, n + 1) { debug(i, lst.get(i, i + 1)); }
		// #endif
		debug(prs);
	}

	return;
}
int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout << std::fixed << std::setprecision(15);
	srand((unsigned)time(NULL));

	int n;
	while(cin >> n && n) {
		solve(n);
	}

	return 0;
}
accuracy: 1
time_ms: 320
memory_kb: 34692
final_rank: 14

code_snippet: #line 2 "library/bits/stdc++.h"

// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif
#line 2 "Source.cpp"
using namespace std;

#define REP(a, b) for (long long a = 0; a < b; ++a)
#define ll long long
#define ld long double
#define ALL(x) begin(x), end(x)

#line 1 "library/atcoder/lazysegtree.hpp"



#line 5 "library/atcoder/lazysegtree.hpp"
#include <cassert>
#line 8 "library/atcoder/lazysegtree.hpp"

#line 1 "library/atcoder/internal_bit.hpp"



#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param n `0 <= n`
// @return minimum non-negative `x` s.t. `n <= 2**x`
int ceil_pow2(int n) {
    int x = 0;
    while ((1U << x) < (unsigned int)(n)) x++;
    return x;
}

// @param n `1 <= n`
// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
int bsf(unsigned int n) {
#ifdef _MSC_VER
    unsigned long index;
    _BitScanForward(&index, n);
    return index;
#else
    return __builtin_ctz(n);
#endif
}

}  // namespace internal

}  // namespace atcoder


#line 10 "library/atcoder/lazysegtree.hpp"

namespace atcoder {

template <class S,
          S (*op)(S, S),
          S (*e)(),
          class F,
          S (*mapping)(F, S),
          F (*composition)(F, F),
          F (*id)()>
struct lazy_segtree {
  public:
    lazy_segtree() : lazy_segtree(0) {}
    explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    explicit lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
        log = internal::ceil_pow2(_n);
        size = 1 << log;
        d = std::vector<S>(2 * size, e());
        lz = std::vector<F>(size, id());
        for (int i = 0; i < _n; i++) d[size + i] = v[i];
        for (int i = size - 1; i >= 1; i--) {
            update(i);
        }
    }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;
    std::vector<F> lz;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f) {
        d[k] = mapping(f, d[k]);
        if (k < size) lz[k] = composition(f, lz[k]);
    }
    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = id();
    }
};

}  // namespace atcoder


#line 10 "Source.cpp"

#define int long long
int op(int a, int b)
{
  return min(a, b);
}
int e()
{
  return 1e9;
}

int mapping(int a, int b)
{
  return a + b;
}
int id() { return 0LL; }

void solve()
{
  int n, query;
  cin >> n >> query;
  atcoder::lazy_segtree<int, op, e, int, mapping, mapping, id> seg(n);
  string s;
  cin >> s;
  int cnt = 0;
  set<int> Up, Down;
  REP(i, n)
  {
    if (s[i] == '(')
    {
      cnt++;
      Up.insert(i);
    }
    else
    {
      cnt--;
      Down.insert(i);
    }
    seg.set(i, cnt);
  }

  REP(i, query)
  {
    int x;
    cin >> x;
    x--;
    if (s[x] == '(')
    {
      s[x] = ')';
      seg.apply(x, n, -2);
      Down.insert(x);
      while (true)
      {
        int y = *Down.begin();
        if (s[y] == ')')
        {
          cout << y + 1 << endl;
          s[y] = '(';
          seg.apply(y, n, +2);
          Up.insert(y);
          break;
        }
        else
        {
          Down.erase(Down.begin());
        }
      }
    }
    else
    {
      s[x] = '(';
      seg.apply(x, n, 2);
      Up.insert(x);

      int bot = n;
      int top = -1;
      while (bot - top > 1)
      {
        int mid = (bot + top) / 2;
        if (seg.prod(mid, n) >= 2)
        {
          bot = mid;
        }
        else
        {
          top = mid;
        }
      }
      cout << bot + 1 << endl;
      s[bot] = ')';
      seg.apply(bot, n, -2);
      Down.insert(bot);
    }
  }
}

#undef int
int main()
{
  iostream::sync_with_stdio(false);
  cout << fixed << setprecision(100);
  solve();
}
accuracy: 1
time_ms: 660
memory_kb: 37104
final_rank: 18

code_snippet: #include <bits/stdc++.h>
#define FOR(i,a,b) for(long long i=a;i<=b;i++)
#define FORD(i,a,b) for(int i=a;i>=b;i--)

using namespace std;

const int mn =  3e5+5;
int n,q;
string s;
int a[mn], b[mn], t[4*mn], tl[mn*4], tr[mn*4], lazy[mn*4];
priority_queue<int > close_;

void build(int i, int l, int r){
    tl[i] = l;
    tr[i] = r;
    if (l==r) t[i] = a[l]; else {
        int m = (l+r) >> 1;
        build(i*2, l, m);
        build(i*2+1, m+1, r);
        t[i] = min(t[i*2], t[i*2+1]);
    }
}

void downLazy(int i){
    if (lazy[i]){
        lazy[i*2] += lazy[i];
        lazy[i*2+1] += lazy[i];

        t[i*2] += lazy[i];
        t[i*2+1] += lazy[i];
        lazy[i] = 0;
    }
}

void update(int i, int u, int diff){
    if (tl[i] >=u){
        t[i] += diff;
        lazy[i] += diff;
        return ;
    }
    if (tr[i] < u) return;
    downLazy(i);

    update(i*2, u, diff);
    update(i*2+1, u, diff);
    t[i] = min(t[i*2], t[i*2+1]);
}

int getMin(int i, int u){
    if (tl[i] >=u) return t[i];
    if (tr[i] < u) return n+1;
    downLazy(i);

    int r1 = getMin(i*2, u);
    int r2 = getMin(i*2+1, u);
    return min(r1, r2);
}

void solve(){
    s = "1"+s;
    FOR(i,1,n) {
        if (s[i]=='(') b[i]=1; else b[i]=-1;
        a[i]=a[i-1]+b[i];
    }
    build(1,1,n);

    FOR(i,1,n) if (b[i]==-1) close_.push(-i);

    FOR(qq,1,q){
        int p ;
        cin >> p;
        if (b[p] == 1) {
            b[p] = -1;
            update(1, p, -2);
            close_.push(-p);

            while (b[-close_.top()]==1) close_.pop();
            int np = -close_.top(); close_.pop();
            b[np] = 1;
            update(1, np, 2);
            cout << np << '\n';
        } else {
            b[p] = 1;
            update(1, p, 2);
            int l = 1;
            int r = p;
            int mid , res;
            while (l<=r){
                mid = (l+r)/2;
                int tmp = getMin(1, mid);
                if (tmp >= 2){
                    res = mid;
                    r = mid-1;
                } else l = mid+1;
            }
            b[res] = -1;
            update(1, res, -2);
            close_.push(-res);
            cout << res << '\n';
        }
    }
}

int     main(){
    cin >> n >> q;
    cin >> s;
    solve();
}
accuracy: 1
time_ms: 670
memory_kb: 24700
final_rank: 12