#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <utility>
#include <cstdio>
#include <iomanip>
#include <iterator>
#include <vector>
#include <map>
#include <set>
#define fi first
#define se second
#define m_p make_pair
#define endl "\n"
using namespace std;
typedef long long ll;
const ll NN=1000001;
ll n,m,i,k,j,f,x,y,z,q,w,e,t1,tt,t2; string s;
ll t[4*NN+1], f1[4*NN+1], f2[4*NN+1];

void modify(int v, int tl, int tr, int pos, int t1, int t2)
{
    if(tl==tr)
    {
        f1[v]=t1;
        f2[v]=t2;
    }
    else
    {
        int c=(tl+tr)>>1;
        if(pos<=c)modify(v*2,tl,c,pos,t1,t2);
        else modify(v*2+1,c+1,tr,pos,t1,t2);
        ll q=min(f1[v*2],f2[v*2+1]);
        t[v]=t[v*2]+(q<<1)+t[v*2+1];
        f1[v]=f1[v*2]-q+f1[v*2+1];
        f2[v]=f2[v*2]-q+f2[v*2+1];
    }
}

void get(int v, int tl, int tr, int l, int r)
{
    if(l>r)return;
    if(tl==r && tr==r)
    {
        ll q=min(t1,f2[v]);
        tt+=(t[v]+(q<<1));
        t1+=(f1[v]-q);
        t2+=(f2[v]-q);
        return;
    }
    int c=(tl+tr)>>1;
    get(v*2,tl,c,l,min(c,r));
    get(v*2+1,c+1,tr,max(l,c+1),r);
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cin >> s; n=s.size();
    for(i=1; i<=n; i++)modify(1,1,n,i,1-abs(s[i-1]-'('),1-abs(s[i-1]-')'));
    cin >> m;
    for(i=1; i<=m; i++)
    {
        cin >> x >> y;
        t1=0; t2=0;
        tt=0; w=0;
        get(1,1,n,x,y);
        cout << tt << endl;
    }
    return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <utility>
#include <cstdio>
#include <iomanip>
#include <iterator>
#include <vector>
#include <map>
#include <set>
#define fi first
#define se second
#define m_p make_pair
#define endl "\n"
using namespace std;
typedef long long ll;
const int NN=1000001;
int n,m,i,k,j,f,x,y,z,q,w,e,t1,tt,t2; string s;
int t[4*NN+1], f1[4*NN+1], f2[4*NN+1];

void modify(int v, int tl, int tr, int pos, int t1, int t2)
{
    if(tl==tr)
    {
        f1[v]=t1;
        f2[v]=t2;
    }
    else
    {
        int c=(tl+tr)>>1;
        if(pos<=c)modify(v*2,tl,c,pos,t1,t2);
        else modify(v*2+1,c+1,tr,pos,t1,t2);
        int q=min(f1[v*2],f2[v*2+1]);
        t[v]=t[v*2]+(q<<1)+t[v*2+1];
        f1[v]=f1[v*2]-q+f1[v*2+1];
        f2[v]=f2[v*2]-q+f2[v*2+1];
    }
}

void get(int v, int tl, int tr, int l, int r)
{
    if(l>r)return;
    if(tl==r && tr==r)
    {
        int q=min(t1,f2[v]);
        tt+=(t[v]+(q<<1));
        t1+=(f1[v]-q);
        t2+=(f2[v]-q);
        return;
    }
    int c=(tl+tr)>>1;
    get(v*2,tl,c,l,min(c,r));
    get(v*2+1,c+1,tr,max(l,c+1),r);
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cin >> s; n=s.size();
    for(i=1; i<=n; i++)
    if(s[i-1]=='(')modify(1,1,n,i,1,0);
    else modify(1,1,n,i,0,1); cin >> m;
    for(i=1; i<=m; i++)
    {
        cin >> x >> y;
        t1=0; t2=0;
        tt=0; w=0;
        get(1,1,n,x,y);
        cout << tt << endl;
    }
    return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <utility>
#include <cstdio>
#include <iomanip>
#include <iterator>
#include <vector>
#include <map>
#include <set>
#define fi first
#define se second
#define m_p make_pair
#define endl "\n"
using namespace std;
typedef long long ll;
const ll NN=1000001;
ll n,m,i,k,j,f,x,y,z,q,w,e,t1,tt,t2; string s;
ll t[4*NN+1], f1[4*NN+1], f2[4*NN+1];

void modify(int v, int tl, int tr, int pos, int t1, int t2)
{
    if(tl==tr)
    {
        f1[v]=t1;
        f2[v]=t2;
    }
    else
    {
        int c=(tl+tr)>>1;
        if(pos<=c)modify(v*2,tl,c,pos,t1,t2);
        else modify(v*2+1,c+1,tr,pos,t1,t2);
        ll q=min(f1[v*2],f2[v*2+1]);
        t[v]=t[v*2]+(q<<1)+t[v*2+1];
        f1[v]=f1[v*2]-q+f1[v*2+1];
        f2[v]=f2[v*2]-q+f2[v*2+1];
    }
}

void get(int v, int tl, int tr, int l, int r)
{
    if(l>r)return;
    if(tl==r && tr==r)
    {
        ll q=min(t1,f2[v]);
        tt+=(t[v]+(q<<1));
        t1+=(f1[v]-q);
        t2+=(f2[v]-q);
        return;
    }
    int c=(tl+tr)>>1;
    get(v*2,tl,c,l,min(c,r));
    get(v*2+1,c+1,tr,max(l,c+1),r);
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); getline(cin,s); n=s.size();
    for(i=1; i<=n; i++)modify(1,1,n,i,1-abs(s[i-1]-'('),1-abs(s[i-1]-')'));
    cin >> m;
    for(i=1; i<=m; i++)
    {
        cin >> x >> y;
        t1=0; t2=0;
        tt=0; w=0;
        get(1,1,n,x,y);
        cout << tt << endl;
    }
    return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <utility>
#include <cstdio>
#include <iomanip>
#include <iterator>
#include <vector>
#include <map>
#include <set>
#define fi first
#define se second
#define m_p make_pair
#define endl "\n"
using namespace std;
typedef long long ll;
const int NN=1000001;
int n,m,i,k,j,f,x,y,z,q,w,e,t1,tt,t2; string s;
int t[4*NN+1], f1[4*NN+1], f2[4*NN+1];

void modify(int v, int tl, int tr, int pos, int t1, int t2)
{
    if(tl==tr)
    {
        f1[v]=t1;
        f2[v]=t2;
    }
    else
    {
        int c=(tl+tr)>>1;
        if(pos<=c)modify(v*2,tl,c,pos,t1,t2);
        else modify(v*2+1,c+1,tr,pos,t1,t2);
        int q=min(f1[v*2],f2[v*2+1]);
        t[v]=t[v*2]+(q<<1)+t[v*2+1];
        f1[v]=f1[v*2]-q+f1[v*2+1];
        f2[v]=f2[v*2]-q+f2[v*2+1];
    }
}

void get(int v, int tl, int tr, int l, int r)
{
    if(l>r)return;
    if(tl==r && tr==r)
    {
        int q=min(t1,f2[v]);
        tt+=(t[v]+(q<<1));
        t1+=(f1[v]-q);
        t2+=(f2[v]-q);
        return;
    }
    int c=(tl+tr)>>1;
    get(v*2,tl,c,l,min(c,r));
    get(v*2+1,c+1,tr,max(l,c+1),r);
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cin >> s; n=s.size();
    for(i=1; i<=n; i++)modify(1,1,n,i,1-abs(s[i-1]-'('),1-abs(s[i-1]-')'));
    cin >> m;
    for(i=1; i<=m; i++)
    {
        cin >> x >> y;
        t1=0; t2=0;
        tt=0; w=0;
        get(1,1,n,x,y);
        cout << tt << endl;
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

char str[1000005];

struct Tree
{
    int open,close,len;
};
Tree tree[4*1000005];

Tree Merge(Tree ob1, Tree ob2)
{
    Tree ob;
    int mn=min(ob1.open,ob2.close);
    ob.len=ob1.len+ob2.len+(mn*2);
    ob.open=ob1.open+ob2.open-mn;
    ob.close=ob1.close+ob2.close-mn;
    return ob;
}

Tree make_data(int op, int cl, int l)
{
    Tree ob;
    ob.open=op;
    ob.close=cl;
    ob.len=l;
    return ob;
}

void build(int node, int b, int e)
{
    if(b==e)
    {
        tree[node].open=(str[b-1]=='(');
        tree[node].close=(str[b-1]==')');
        tree[node].len=0;
        return;
    }
    int mid=(b+e)>>1;
    int Left=node<<1;
    int Right=Left+1;
    build(Left, b, mid);
    build(Right, mid+1, e);
    tree[node]=Merge(tree[Left],tree[Right]);
}

Tree query(int node, int b, int e, int i, int j)
{
    if(i>e || j<b) return make_data(0,0,0);
    if(b>=i && e<=j) return tree[node];
    int mid=(b+e)>>1;
    int Left=node<<1;
    int Right=Left+1;
    Tree p1=query(Left, b, mid, i, j);
    Tree p2=query(Right, mid+1, e, i, j);
    return Merge(p1,p2);
}

int main()
{
    int n,i,j,l,r;
    scanf("%s %d",str,&n);
    int x=strlen(str);
    build(1,1,x);
    while(n--)
    {
        scanf("%d %d",&l,&r);
        Tree ans=query(1,1,x,l,r);
        printf("%d\n",ans.len);
    }
    return 0;
}


#include<bits/stdc++.h>
#define PI 3.141592653589793238462
using namespace std;
typedef long long ll;
typedef long double db;
string s;
struct Tree{int l,r,mx,numl,numr;}tree[4000005];
Tree pushup(Tree lx,Tree rx){
    Tree now={0,0,0,0,0};
    int x=min(lx.numl,rx.numr);
    now.mx=x+lx.mx+rx.mx;
    now.numl=lx.numl+rx.numl-x;
    now.numr=lx.numr+rx.numr-x;
    now.l=lx.l;now.r=rx.r;return now;
}
void buildtree(int i,int l,int r){
    tree[i].l=l;tree[i].r=r;tree[i].mx=0;
    if(l==r){
        if(s[l]==')') tree[i].numr=1;
        if(s[l]=='(') tree[i].numl=1;
        return;
    }
    buildtree(i*2,l,(l+r)/2);
    buildtree(i*2+1,(l+r)/2+1,r);
    tree[i]=pushup(tree[i*2],tree[i*2+1]);
}
Tree query(int i,int l,int r){
    if(tree[i].l>=l&&r>=tree[i].r){
        return tree[i];
    }
    int mid=(tree[i].l+tree[i].r)/2;
    Tree lx={0,0,0,0,0},rx={0,0,0,0,0};
    if(l<=mid) lx=query(i*2,l,r);
    if(r>mid) rx=query(i*2+1,l,r);
    return pushup(lx,rx);
}
int main(){
    cin>>s;
    int q,n=s.length(),l=0;cin>>q;s=" "+s;
    buildtree(1,1,n);
    while(q--){
        int l,r;cin>>l>>r;
        Tree ans=query(1,l,r);
        cout<<ans.mx*2<<endl;
    }
}


#include<bits/stdc++.h>
#define pii pair<int,pair<int,int>>
using namespace std;
int tree[4000009][3];
int a[1000009];

void init(int node,int b,int e)
{
	if(b==e)
	{
		tree[node][a[b]]=1;
		tree[node][1-a[b]]=0;
		tree[node][2]=0;
		return;
	}
	int mid=(b+e)/2;
	int left=node*2;
	int right=node*2+1;
	init(left,b,mid);
	init(right,mid+1,e);

	tree[node][2]=min(tree[left][0],tree[right][1]);
	tree[node][0]=tree[left][0]-tree[node][2]+tree[right][0];
	tree[node][1]=tree[left][1]+tree[right][1]-tree[node][2];
	tree[node][2]+=tree[left][2]+tree[right][2];

}
pii query(int node,int b,int e, int l,int r)
{
	if(l>e || r<b)return {0,{0,0}};
	if(b>=l && e<=r)return {tree[node][2],{tree[node][0],tree[node][1]}};

	int mid=b+e>>1;

	int left=node*2;
	int right=node*2 +1;
	pii p1=query(left,b,mid,l,r);
	pii p2=query(right,mid+1,e,l,r);
	int mn=min(p1.second.first,p2.second.second);
	int tot=p1.first+p2.first+mn;
	int lf=p1.second.first+p2.second.first-mn;
	int rf=p1.second.second+p2.second.second-mn;
	return {tot,{lf,rf}};
}
int main()
{
	string s;
	cin>>s;
	int n=s.length();
	for(int i=0;i<n;i++)
	{
		if(s[i]=='(')a[i+1]=0;
		else a[i+1]=1;
	}
	int q;
	cin>>q;

	init(1,1,n);

	while(q--)
	{
		int l,r;
		cin>>l>>r;
		cout<<2*query(1,1,n,l,r).first<<endl;

	}
}


#include <bits/stdc++.h>

#define int          long long
#define pb          push_back
#define pii         pair<int,int>
#define vi          vector<int>
#define vii         vector<pii>
#define mi          map<int,int>
#define mii         map<pii,int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (int)x.size()
#define endl        '\n'
#define MOD         1000000007
#define mem(x)      memset(x,0,sizeof(x));
#define what_is(x)  cout << #x << " is " << x << flush << endl;
#define rep(i,a,b)  for(int i=a;i<b;i++)

using namespace std;
const int maxn = 1000100;
int n, k, a[maxn];
string s;

struct t
{
	int open = 0, close = 0, ans = 0;
}tree[4*maxn], ft;

t merge(t x, t y)
{
	t temp;
	temp.ans = x.ans + y.ans + min(x.open, y.close);
	temp.open = x.open + y.open - min(x.open, y.close);
	temp.close = x.close + y.close - min(x.open, y.close);
	return temp;

}

void build(int node, int start, int end)
{
	if(start>end)return;
	if(start == end)
	{
		if(s[start] == '(')
		tree[node].open++;
		else tree[node].close++;
		return;
	}
	int mid = (start+end)/2;
	build(2*node, start, mid);
	build(2*node+1, mid+1, end);
	tree[node] = merge(tree[2*node], tree[2*node+1]);
}

t query(int node, int start, int end, int l, int r)
{
	if(start>end || start>r || l>end)return ft;
	if(l<=start && end<=r)
		return tree[node];
	int mid = (start+end)/2;
	t p1 = query(2*node, start, mid, l, r);
	t p2 = query(2*node+1, mid+1, end, l, r);
	return merge(p1, p2);
}

void solve(){
	cin>>s;
	n = s.length();
	build(1, 0, n-1);
	cin>>k;
	while(k--)
	{
		int x,y;cin>>x>>y;x--;y--;
		cout<<2*query(1, 0, n-1, x, y).ans<<endl;
	}

}
signed main(){
	#ifndef ONLINE_JUDGE
    // for getting input from input.txt
    freopen("input.txt", "r", stdin);
    // for writing output to output.txt
    freopen("output.txt", "w", stdout);
    #endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int t=1;
    //cin>>t;
    for(int i = 1; i <= t; i++){
        solve();
    }
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>   //PBDS
#include <ext/pb_ds/tree_policy.hpp>       //PBDS
#define int long long int
#define vi vector<int>
#define vii vector<pair<int,int>>
#define pi pair<int,int>
#define deb(x) cerr<<#x<<" : "<<x<<endl;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define mi map<int,int>
#define PI   3.141592653589
#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define f(i,x,n) for(int i=x;i<n;i++)
#define rf(i,x,n) for(int i=n-1;i>=x;i--)
#define check(x)   cerr<<#x<<" : "<<x<<endl;
#define ordered_set tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>
#define fbo find_by_order                    //return iterator PBDS
#define ook order_of_key                     //return number :)) PBDS
#define baar exit(0)
#define INF 1000000000000000000
using namespace __gnu_pbds;
using namespace std;
const int N=1e6+5;
struct node1
{
	int a,b,c;
};
node1 segtree[4*N];
int n;
string s;
void build(int node,int start,int end)
{
	if(start==end)
	{
		if(s[start]=='(')
		{
			segtree[node].a=1;
			segtree[node].b=0;
			segtree[node].c=0;
		}
		else
		{
			segtree[node].a=0;
			segtree[node].b=0;
			segtree[node].c=1;
		}
		return ;
	}
   int mid= start+end;
   mid/=2;
   build(2*node+1,start,mid);
   build(2*node+2,mid+1,end);
   int ans=min({segtree[2*node+1].a,segtree[2*node+2].c});
   segtree[node].b=segtree[2*node+1].b+segtree[2*node+2].b+(2*ans);
   segtree[node].a=segtree[2*node+1].a+segtree[2*node+2].a-ans;
   segtree[node].c=segtree[2*node+1].c+segtree[2*node+2].c-ans;
}
node1 query(int node,int start,int end,int l,int r)
{
	node1 final;
	final.a=0;
	final.b=0;
	final.c=0;
	if(end<l or start>r) return final;
	if(start>=l && end<=r) return segtree[node];
	int mid=start+end;
	mid/=2;
	node1 one=query(2*node+1,start,mid,l,r);
	node1 two=query(2*node+2,mid+1,end,l,r);
	final.b=one.b+two.b;
	int ans1=min(one.a,two.c);
	final.b+=2*ans1;
	final.a=one.a+two.a-ans1;
	final.c=one.c+two.c-ans1;
	return final;
}
signed main()
{
	int q;
	cin>>s>>q;
	n=s.length();
	build(0,0,n-1);
	while(q--)
	{
		int x,y;
		cin>>x>>y;
		node1 seg=query(0,0,n-1,x-1,y-1);
		cout<<seg.b<<endl;
	}
	return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>   //PBDS
#include <ext/pb_ds/tree_policy.hpp>       //PBDS
#define int long long int
#define vi vector<int>
#define vii vector<pair<int,int>>
#define pi pair<int,int>
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define pf push_front
#define deb(x) cerr<<#x<<" : "<<x<<endl;
#define fi first
#define se second
#define mi map<int,int>
#define PI   3.141592653589
#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define f(i,x,n) for(int i=x;i<n;i++)
#define rf(i,x,n) for(int i=n-1;i>=x;i--)
#define check(x)   cerr<<#x<<" : "<<x<<endl;
#define ordered_set tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>
#define fbo find_by_order                    //return iterator PBDS
#define ook order_of_key                     //return number :)) PBDS
#define baar exit(0)
using namespace __gnu_pbds;
using namespace std;
int powmod(int base,int exponent,int mod)
{
	int ans=1;
	while(exponent){
		if(exponent&1)ans=(ans*base)%mod;
		base=(base*base)%mod;
		exponent/=2;
	}
	return ans;
}
signed main()
{
  fast
  string s;
  cin>>s;
  vector<int>v1,v2;
  stack<int>s1;
  f(i,0,s.length())
  {
  	if(s[i]=='(')
  	{
  		s1.push(i);
	}
	else if(!s1.empty())
	{
		int x=s1.top();
		s1.pop();
		v1.pb(x+1);
		v2.pb(i+1);
	}
  }
  sort(all(v1));
  sort(all(v2));
  int q;
  cin>>q;
  while(q--)
  {
  	int l,r;
  	cin>>l>>r;
  	int ind3=lower_bound(all(v1),l)-v1.begin();
  	if(ind3==v1.size())
  	{
  		cout<<0<<endl;
  		continue;
	}
  	int ind1=lower_bound(all(v2),v1[ind3])-v2.begin();
  	if(ind1==v2.size())
  	{
  	  cout<<0<<endl;
	  continue;
	}
	int ind2=lower_bound(all(v2),r)-v2.begin();
	if(ind2==v2.size()) ind2--;
	if(v2[ind2]>r) ind2--;
	int ind4=lower_bound(all(v1),v2[ind2])-v1.begin();
	if(ind4==v1.size()) ind4--;
	if(v1[ind4]>v2[ind2]) ind4--;
	int dif1=ind2-ind1+1;
	int dif2=ind4-ind3+1;
	int ans=min(dif1,dif2);
	if(ans<=0) cout<<0<<endl;
	else cout<<2*ans<<endl;
  }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>   //PBDS
#include <ext/pb_ds/tree_policy.hpp>       //PBDS
#define int long long int
#define vi vector<int>
#define vii vector<pair<int,int>>
#define pi pair<int,int>
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define pf push_front
#define deb(x) cerr<<#x<<" : "<<x<<endl;
#define fi first
#define se second
#define mi map<int,int>
#define PI   3.141592653589
#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define f(i,x,n) for(int i=x;i<n;i++)
#define rf(i,x,n) for(int i=n-1;i>=x;i--)
#define check(x)   cerr<<#x<<" : "<<x<<endl;
#define ordered_set tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>
#define fbo find_by_order                    //return iterator PBDS
#define ook order_of_key                     //return number :)) PBDS
#define baar exit(0)
using namespace __gnu_pbds;
using namespace std;
int powmod(int base,int exponent,int mod)
{
	int ans=1;
	while(exponent){
		if(exponent&1)ans=(ans*base)%mod;
		base=(base*base)%mod;
		exponent/=2;
	}
	return ans;
}
const int N=1e6+5;
vi BIT(N);
vi equal1[N];
vector<pi>l[N],r[N];
vi ans(100005);
void update(int i)
{
	while(i<N)
	{
		BIT[i]+=1;
		i+=(i & -i);
	}
}
int sum(int i)
{
	int sum1=0;
	while(i>0)
	{
		sum1+=BIT[i];
		i-= (i & -i);
	}
	return sum1;
}
signed main()
{
   fast
   string s;
   cin>>s;
   stack<int>s1;
   int n=s.length();
   f(i,0,n)
   {
   	if(s[i]=='(')
   	{
   		s1.push(i+1);
	}
	else
	{
		if(!s1.empty())
		{
			int x=s1.top();
			s1.pop();
			equal1[x].pb(i+1);
		}
	}
   }
   int q;
   cin>>q;
   f(i,0,q)
   {
   	int x,y;
   	cin>>x>>y;
   	l[x].pb({y,i});
   	r[y].pb({x,i});
   }
   f(i,1,n+1)
   {
   	for(auto x:l[i]) ans[x.se]-=sum(x.fi);
   	for(auto x:equal1[i]) update(x);
   	for(auto x:r[i]) ans[x.se]+=sum(i);
   }
   f(i,0,q) cout<<2*ans[i]<<endl;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>   //PBDS
#include <ext/pb_ds/tree_policy.hpp>       //PBDS
#define int long long int
#define vi vector<int>
#define vii vector<pair<int,int>>
#define pi pair<int,int>
#define deb(x) cerr<<#x<<" : "<<x<<endl;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define mi map<int,int>
#define PI   3.141592653589
#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define f(i,x,n) for(int i=x;i<n;i++)
#define rf(i,x,n) for(int i=n-1;i>=x;i--)
#define check(x)   cerr<<#x<<" : "<<x<<endl;
#define ordered_set tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>
#define fbo find_by_order                    //return iterator PBDS
#define ook order_of_key                     //return number :)) PBDS
#define baar exit(0)
#define INF 1000000000000000000
using namespace __gnu_pbds;
using namespace std;
const int N=1e6+5;
struct node1
{
	int a,b,c;
};
node1 segtree[4*N];
int n;
string s;
void build(int node,int start,int end)
{
	if(start==end)
	{
		if(s[start]=='(')
		{
			segtree[node].a=1;
			segtree[node].b=0;
			segtree[node].c=0;
		}
		else
		{
			segtree[node].a=0;
			segtree[node].b=0;
			segtree[node].c=1;
		}
		return ;
	}
   int mid= start+end;
   mid/=2;
   build(2*node+1,start,mid);
   build(2*node+2,mid+1,end);
   int ans=min({segtree[2*node+1].a,segtree[2*node+2].c});
   segtree[node].b=segtree[2*node+1].b+segtree[2*node+2].b+(2*ans);
   segtree[node].a=segtree[2*node+1].a+segtree[2*node+2].a-ans;
   segtree[node].c=segtree[2*node+1].c+segtree[2*node+2].c-ans;
}
node1 query(int node,int start,int end,int l,int r)
{
	node1 final;
	final.a=0;
	final.b=0;
	final.c=0;
	if(end<l or start>r) return final;
	if(start>=l && end<=r) return segtree[node];
	int mid=start+end;
	mid/=2;
	node1 one=query(2*node+1,start,mid,l,r);
	node1 two=query(2*node+2,mid+1,end,l,r);
	final.b=one.b+two.b;
	int ans1=min(one.a,two.c);
	final.b+=2*ans1;
	final.a=one.a+two.a-ans1;
	final.c=one.c+two.c-ans1;
	return final;
}
signed main()
{
	fast
	int q;
	cin>>s>>q;
	n=s.length();
	build(0,0,n-1);
	while(q--)
	{
		int x,y;
		cin>>x>>y;
		node1 seg=query(0,0,n-1,x-1,y-1);
		cout<<seg.b<<endl;
	}
	return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>   //PBDS
#include <ext/pb_ds/tree_policy.hpp>       //PBDS
#define int long long int
#define vi vector<int>
#define vii vector<pair<int,int>>
#define pi pair<int,int>
#define deb(x) cerr<<#x<<" : "<<x<<endl;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define mi map<int,int>
#define PI   3.141592653589
#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define f(i,x,n) for(int i=x;i<n;i++)
#define rf(i,x,n) for(int i=n-1;i>=x;i--)
#define check(x)   cerr<<#x<<" : "<<x<<endl;
#define ordered_set tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>
#define fbo find_by_order                    //return iterator PBDS
#define ook order_of_key                     //return number :)) PBDS
#define baar exit(0)
#define INF 1000000000000000000
using namespace __gnu_pbds;
using namespace std;
const int N=1e5+5;
struct node1
{
	int a,b,c;
};
node1 segtree[4*N];
int n;
string s;
void build(int node,int start,int end)
{
	if(start==end)
	{
		if(s[start]=='(')
		{
			segtree[node].a=1;
			segtree[node].b=0;
			segtree[node].c=0;
		}
		else
		{
			segtree[node].a=0;
			segtree[node].b=0;
			segtree[node].c=1;
		}
		return ;
	}
   int mid= start+end;
   mid/=2;
   build(2*node+1,start,mid);
   build(2*node+2,mid+1,end);
   int ans=min({segtree[2*node+1].a,segtree[2*node+2].c});
   segtree[node].b=segtree[2*node+1].b+segtree[2*node+2].b+(2*ans);
   segtree[node].a=segtree[2*node+1].a+segtree[2*node+2].a-ans;
   segtree[node].c=segtree[2*node+1].c+segtree[2*node+2].c-ans;
}
node1 query(int node,int start,int end,int l,int r)
{
	node1 final;
	final.a=0;
	final.b=0;
	final.c=0;
	if(end<l or start>r) return final;
	if(start>=l && end<=r) return segtree[node];
	int mid=start+end;
	mid/=2;
	node1 one=query(2*node+1,start,mid,l,r);
	node1 two=query(2*node+2,mid+1,end,l,r);
	final.b=one.b+two.b;
	int ans1=min(one.a,two.c);
	final.b+=2*ans1;
	final.a=one.a+two.a-ans1;
	final.c=one.c+two.c-ans1;
	return final;
}
signed main()
{
	int q;
	cin>>s>>q;
	n=s.length();
	build(0,0,n-1);
	while(q--)
	{
		int x,y;
		cin>>x>>y;
		node1 seg=query(0,0,n-1,x-1,y-1);
		cout<<seg.b<<endl;
	}
	return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 100005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=s[L]=='('?Data(1,0,0):Data(0,1,0);return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    IOS

    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    scanf("%d",&q);

    while(q--)
    {
        int L,R;
        scanf("%d %d",&L,&R);
        printf("%d\n",query(1,1,Size,L,R).Max);
    }

    return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 1000005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=(s[L]=='('?Data(1,0,0):Data(0,1,0));return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    IOS
    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    cin>>q;

    while(q--)
    {
        int L,R;
        cin>>L>>R;
        cout<<query(1,1,Size,L,R).Max<<endl;
    }

    return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 1000005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=(s[L]=='('?Data(1,0,0):Data(0,1,0));return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    cin>>q;
    //scanf("%d",&q);

    while(q--)
    {
        int L,R;
        cin>>L>>R;
        cout<<query(1,1,Size,L,R).Max<<endl;
        //scanf("%d %d",&L,&R);
        //printf("%d\n",query(1,1,Size,L,R).Max);
    }

    return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 1000005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=(s[L]=='('?Data(1,0,0):Data(0,1,0));return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    scanf("%d",&q);

    while(q--)
    {
        int L,R;
        scanf("%d %d",&L,&R);
        printf("%d\n",query(1,1,Size,L,R).Max);
    }

    return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 1000005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=(s[L]=='('?Data(1,0,0):Data(0,1,0));return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    scanf("%d",&q);

    while(q--)
    {
        int L,R;
        scanf("%d %d",&L,&R);
        printf("%d\n",query(1,1,Size,L,R).Max);
    }

    return 0;
}


/***********************************************************|
|          /\           /-------|   -----    |-----------|  |
|         /  \         /              |      |              |
|        /    \       |               |      |              |
|       /      \      |----|          |      |-------|      |
|      / ------ \          |-----|    |      |              |
|     /          \               |    |      |              |
|    /            \              /    |      |              |
|  ---            --- |---------/   -----  -----            |
|                                                           |
|   Codeforces = Asif_Watson  ||  Codechef = asif_watson    |
|   Mail = ashfaqislam33@gmail.com                          |
|   CSTE, Noakhali Science and Technology University(11)    |
|                                                           |
************************************************************/

#include "bits/stdc++.h"
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;

long long bigmod(long long b, long long p, long long m)
{
    if(p==0)return 1;
    if(p%2==0)
    {
        long long c = bigmod(b, p/2, m);
        return ((c%m)*(c%m))%m;
    }
    else return ((b%m)*(bigmod(b, p-1, m)))%m;
}

template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);}
template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);}

bool Reverse(long long a,long long b){return a>b;}

bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}

#define maxn 100005

struct Data
{
    int Open,Close,Max;
    Data(){}
    Data(int a,int b,int c){Open=a;Close=b;Max=c;}
};

string s;
Data tree[4*maxn];

Data Merge(Data a, Data b)
{
    int fullBalance=min(a.Open,b.Close);
    int OpenLeft=a.Open+b.Open-fullBalance;
    int CloseLeft=a.Close+b.Close-fullBalance;
    return Data(OpenLeft,CloseLeft,a.Max+b.Max+fullBalance*2);
}

void build(int node, int L, int R)
{
    if(L==R){tree[node]=s[L]=='('?Data(1,0,0):Data(0,1,0);return;}
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    build(leftNode,L,mid);
    build(rightNode,mid+1,R);
    tree[node]=Merge(tree[leftNode],tree[rightNode]);
}

Data query(int node, int L, int R, int l, int r)
{
    if(l>R || r<L)return Data(0,0,0);
    if(L>=l && R<=r)return tree[node];
    int leftNode=node*2;
    int rightNode=node*2+1;
    int mid=(L+R)/2;
    Data p1=query(leftNode,L,mid,l,r);
    Data p2=query(rightNode,mid+1,R,l,r);
    return Merge(p1,p2);
}

int main()
{
    cin>>s;
    int Size=s.size();
    s=" "+s;

    build(1,1,Size);

    int q;
    scanf("%d",&q);

    while(q--)
    {
        int L,R;
        scanf("%d %d",&L,&R);
        printf("%d\n",query(1,1,Size,L,R).Max);
    }

    return 0;
}


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

typedef long long ll;

#define        optimize           ios::sync_with_stdio(0); cin.tie(0);
#define PI    acos(-1.0)
#define pb push_back
#define YES cout<<"YES"<<endl;
#define NO cout<<"NO"<<endl;
#define RESET(a, b) memset(a, b, sizeof(a))
#define pii pair <int, int>
#define pll pair <ll, ll>
#define gcd(a, b) __gcd(a, b)

#define        MX        1000005

struct X
{
    ll val, l, r;
};
X zero;
string str;
X tree[MX*4];

void build(int node, int b, int e)
{
    if(b == e){
        if(str[b] == '(') tree[node].l++;
        else tree[node].r++;
        return;
    }

    int left = (node<<1);
    int right = (node<<1) + 1;
    int mid = (b+e)>>1;

    build(left, b, mid);
    build(right, mid+1, e);

    tree[node].val = tree[left].val + tree[right].val;

    ll p = min(tree[left].l, tree[right].r);

    tree[node].val += p;
    tree[node].l = tree[right].l+tree[left].l-p;
    tree[node].r = tree[left].r + tree[right].r-p;
}

X query(int node, int b, int e, int i, int j)
{
    if(b > j || e < i) return zero;
    if(b >= i && e <= j) return tree[node];

    int left = node<<1;
    int right = (node<<1) + 1;
    int mid = (b+e)>>1;

    X p1 = query(left, b, mid, i, j);
    X p2 = query(right, mid+1, e, i, j);
    X ans;

    ans.val = p1.val + p2.val;

    ll p = min(p1.l, p2.r);

    ans.val += p;
    ans.l = p2.l + p1.l - p;
    ans.r = p1.r + p2.r - p;
    return ans;
}

int main()
{
    optimize
    string temp;
    cin>>temp;
    str = '?' + temp;
    ll n = str.size()-1;

    build(1, 1, n);
//    for(int i = 1; i <= 7; i++) cout<<i<<' '<<tree[i].val<<' '<<tree[i].l<<' '<<tree[i].r<<endl;
    int q;
    cin>>q;
    while(q--){
        int l, r;
        cin>>l>>r;
        cout<<(query(1, 1, n, l, r)).val * 2<<endl;
    }
}


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

typedef long long ll;

#define        optimize           ios::sync_with_stdio(0); cin.tie(0);
#define PI    acos(-1.0)
#define pb push_back
#define YES cout<<"YES"<<endl;
#define NO cout<<"NO"<<endl;
#define RESET(a, b) memset(a, b, sizeof(a))
#define pii pair <int, int>
#define pll pair <ll, ll>
#define gcd(a, b) __gcd(a, b)

#define        MX        200005

struct X
{
    ll val, l, r;
};
X zero;
string str;
X tree[MX*4];

void build(int node, int b, int e)
{
    if(b == e){
        if(str[b] == '(') tree[node].l++;
        else tree[node].r++;
        return;
    }

    int left = (node<<1);
    int right = (node<<1) + 1;
    int mid = (b+e)>>1;

    build(left, b, mid);
    build(right, mid+1, e);

    tree[node].val = tree[left].val + tree[right].val;

    ll p = min(tree[left].l, tree[right].r);

    tree[node].val += p;
    tree[node].l = tree[right].l+tree[left].l-p;
    tree[node].r = tree[left].r + tree[right].r-p;
}

X query(int node, int b, int e, int i, int j)
{
    if(b > j || e < i) return zero;
    if(b >= i && e <= j) return tree[node];

    int left = node<<1;
    int right = (node<<1) + 1;
    int mid = (b+e)>>1;

    X p1 = query(left, b, mid, i, j);
    X p2 = query(right, mid+1, e, i, j);
    X ans;

    ans.val = p1.val + p2.val;

    ll p = min(p1.l, p2.r);

    ans.val += p;
    ans.l = p2.l + p1.l - p;
    ans.r = p1.r + p2.r - p;
    return ans;
}

int main()
{
    optimize
    string temp;
    cin>>temp;
    str = '?' + temp;
    ll n = str.size()-1;

    build(1, 1, n);
//    for(int i = 1; i <= 7; i++) cout<<i<<' '<<tree[i].val<<' '<<tree[i].l<<' '<<tree[i].r<<endl;
    int q;
    cin>>q;
    while(q--){
        int l, r;
        cin>>l>>r;
        cout<<(query(1, 1, n, l, r)).val * 2<<endl;
    }
}


#include <bits/stdc++.h>
#define scan(x) for(auto &num:x) cin>>num;
#define print(x) for(auto num:x) cout<<num<<' ';
#define all(x) x.begin(),x.end()
using namespace std;
using ll = long long;
int N=1e6;
struct node
{
	int left,right,balance;
	node()
	{
		left=right=balance=0;
	}
};
vector<node> tree(4*N);
void build(string &s,int low,int high,int ind)
{
	if(low>high)
	return;
	if(low==high)
	{
		node nn;
		if(s[low]=='(')
		{
			nn.left++;
		}
		else
		{
			nn.right++;
		}
		tree[ind]=nn;
		return;
	}
	int mid = low+(high-low)/2;
	build(s,low,mid,2*ind+1);
	build(s,mid+1,high,2*ind+2);
	node L = tree[2*ind+1];
	node R = tree[2*ind+2];
	node curr;
	int add = min(L.left,R.right);
	L.left-=add;
	R.right-=add;
	curr.left = L.left+R.left;
	curr.right=L.right+R.right;
	curr.balance=2*add+L.balance+R.balance;
	tree[ind]=curr;
}
node range(int low,int high,int l,int r,int ind)
{
	if(low>high)
	return node();
	if(r<low||l>high)
	return node();
	if(l<=low&&high<=r)
	{

		return tree[ind];
	}
	int mid = low+(high-low)/2;
	node L = range(low,mid,l,r,2*ind+1);
	node R = range(mid+1,high,l,r,2*ind+2);
	node curr;
	int add = min(L.left,R.right);
	L.left-=add;
	R.right-=add;
	curr.left = L.left+R.left;
	curr.right=L.right+R.right;
	curr.balance=2*add+L.balance+R.balance;
	return curr;
}
int main()
{
//	freopen("input.txt","r",stdin);
	string s;
	cin>>s;
	int q;
	cin>>q;
	build(s,0,s.length()-1,0);
	while(q--)
	{
		int L,R;
		cin>>L>>R;
		node ans = range(0,s.length()-1,L-1,R-1,0);
		cout<<ans.balance<<endl;
	}
	return 0;
}


#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <map>
#include <vector>
#include <cstring>
#include <iomanip>
#include <set>
#include <sstream>
#include <ctime>

#define rust(a, b, c, d) sqrt(sqr(a - c) + sqr(b - d))

#define sqr(a) (a)*(a)
#define m_p make_pair
#define fi first
#define se second
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)

typedef long long ll;
const int MAXINT=2147483640;
const ll MAXLL=9223372036854775800LL;
const ll MAXN=1000000;

using namespace std;

struct {
    ll ans, open, close;
}
t[MAXN], res;
ll l, r;

void modify(ll v, ll tl, ll tr, ll pos, ll v1, ll v2) {
    if (tl == tr) {
        t[v].open = v1;
        t[v].close = v2;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (pos <= tm) modify(v * 2, tl, tm, pos, v1, v2);
    else modify(v * 2 + 1, tm + 1, tr, pos, v1, v2);
    ll k = min(t[v * 2].open, t[v * 2 + 1].close);
    t[v].ans = t[v * 2].ans + t[v * 2 + 1].ans + k * 2;
    t[v].open = t[v * 2].open + t[v * 2 + 1].open - k;
    t[v].close = t[v * 2].close + t[v * 2 + 1].close - k;
}

void get(ll v, ll tl, ll tr) {
    if (tl >= l && tr <= r) {
        ll k = min(res.open, t[v].close);
        res.ans = res.ans + t[v].ans + k * 2;
        res.open = res.open - k + t[v].open;
        res.close = res.close - l + t[v].close;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (l <= tm && r >= tl) get(v * 2, tl, tm);
    if (l <= tr && r > tm) get(v * 2 + 1, tm + 1, tr);
}

int main()
{
    fast_io;

    string s;
    ll i, j, n, m;
    cin >> s;
    n = s.size();
    for (i = 0; i < n; ++i) {
        if (s[i] == '(')modify(1, 1, n, i + 1, 1, 0);
        else modify(1, 1, n, i + 1, 0, 1);
    }
    cout << "kek: " << t[1].ans << endl;
    cin >> m;
    for (i = 1; i <= m; ++i) {
        cin >> l >> r;
        res.ans = 0;
        res.open = 0;
        res.close = 0;
        get(1, 1, n);
        cout << res.ans << endl;
    }
    return 0;
}


#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <map>
#include <vector>
#include <cstring>
#include <iomanip>
#include <set>
#include <sstream>
#include <ctime>

#define rust(a, b, c, d) sqrt(sqr(a - c) + sqr(b - d))

#define sqr(a) (a)*(a)
#define m_p make_pair
#define fi first
#define se second
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)

typedef long long ll;
const int MAXINT=2147483640;
const ll MAXLL=9223372036854775800LL;
const ll MAXN=1000000;

using namespace std;

struct {
    ll ans, open, close;
}
t[MAXN], res;
ll l, r;

void modify(ll v, ll tl, ll tr, ll pos, ll v1, ll v2) {
    if (tl == tr) {
        t[v].open = v1;
        t[v].close = v2;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (pos <= tm) modify(v * 2, tl, tm, pos, v1, v2);
    else modify(v * 2 + 1, tm + 1, tr, pos, v1, v2);
    ll k = min(t[v * 2].open, t[v * 2 + 1].close);
    t[v].ans = t[v * 2].ans + t[v * 2 + 1].ans + k * 2;
    t[v].open = t[v * 2].open + t[v * 2 + 1].open - k;
    t[v].close = t[v * 2].close + t[v * 2 + 1].close - k;
}

void get(ll v, ll tl, ll tr) {
    if (tl >= l && tr <= r) {
        ll k = min(res.open, t[v].close);
        res.ans = res.ans + t[v].ans + k * 2;
        res.open = res.open - k + t[v].open;
        res.close = res.close - l + t[v].close;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (l <= tm && r >= tl) get(v * 2, tl, tm);
    if (l <= tr && r > tm) get(v * 2 + 1, tm + 1, tr);
}

int main()
{
    fast_io;

    string s;
    ll i, j, n, m;
    cin >> s;
    n = s.size();
    for (i = 0; i < n; ++i) {
        if (s[i] == '(')modify(1, 1, n, i + 1, 1, 0);
        else modify(1, 1, n, i + 1, 0, 1);
    }

    cin >> m;
    for (i = 1; i <= m; ++i) {
        cin >> l >> r;
        res.ans = 0;
        res.open = 0;
        res.close = 0;
        get(1, 1, n);
        cout << res.ans << endl;
    }
    return 0;
}


#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <map>
#include <vector>
#include <cstring>
#include <iomanip>
#include <set>
#include <sstream>
#include <ctime>

#define rust(a, b, c, d) sqrt(sqr(a - c) + sqr(b - d))

#define sqr(a) (a)*(a)
#define m_p make_pair
#define fi first
#define se second
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)

typedef long long ll;
const int MAXINT=2147483640;
const ll MAXLL=9223372036854775800LL;
const ll MAXN=4000000;

using namespace std;

struct {
    ll ans, open, close;
}
t[MAXN], res;
ll l, r;

void modify(ll v, ll tl, ll tr, ll pos, ll v1, ll v2) {
    if (tl == tr) {
        t[v].open = v1;
        t[v].close = v2;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (pos <= tm) modify(v * 2, tl, tm, pos, v1, v2);
    else modify(v * 2 + 1, tm + 1, tr, pos, v1, v2);
    ll k = min(t[v * 2].open, t[v * 2 + 1].close);
    t[v].ans = t[v * 2].ans + t[v * 2 + 1].ans + k * 2;
    t[v].open = t[v * 2].open + t[v * 2 + 1].open - k;
    t[v].close = t[v * 2].close + t[v * 2 + 1].close - k;
}

void get(ll v, ll tl, ll tr) {
    if (tl >= l && tr <= r) {
        ll k = min(res.open, t[v].close);
        res.ans = res.ans + t[v].ans + k * 2;
        res.open = res.open - k + t[v].open;
        res.close = res.close - l + t[v].close;
        return;
    }
    ll tm = (tl + tr) / 2;
    if (l <= tm && r >= tl) get(v * 2, tl, tm);
    if (l <= tr && r > tm) get(v * 2 + 1, tm + 1, tr);
}

int main()
{
    fast_io;

    string s;
    ll i, j, n, m;
    cin >> s;
    n = s.size();
    for (i = 0; i < n; ++i) {
        if (s[i] == '(')modify(1, 1, n, i + 1, 1, 0);
        else modify(1, 1, n, i + 1, 0, 1);
    }

    cin >> m;
    for (i = 1; i <= m; ++i) {
        cin >> l >> r;
        res.ans = 0;
        res.open = 0;
        res.close = 0;
        get(1, 1, n);
        cout << res.ans << endl;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
char g[N+1];
int cm[N+1];

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    int root = sqrt(n);
    int const ct = (n+root-1)/root;
    stack<char>st[ct+5];
    for(int i = 0; i<n; ++i){
         if(st[i/root].size() && st[i/root].top() == '(' && g[i] == ')')cm[i/root] += 2, st[i/root].pop();
         else {
          st[i/root].push(g[i]);
        }
    }
    scanf("%d",&m);
    for(int i = 0, l,r; i < m ; ++i){
         scanf("%d%d",&l,&r);
         --l,--r;
         int an = 0, lst = 0;
         stack<char>prv;
         for(int j = l; j<=r; ++j){
             if(j % root == 0 && j + root - 1 >= l && j + root - 1 <= r){
                  an += cm[j/root];
                  j += root - 1;
                  lst = j/root;
                  stack<char>cur = st[lst];
                  string c = "";
                  while(cur.size()){
                      c += cur.top();
                      cur.pop();
                  }
                  for(int k = c.size()-1; k>=0;--k){
                       if(prv.size() && prv.top() == '(' && c[k] == ')')prv.pop(),an += 2;
                       else prv.push(c[k]);
                  }
             }
             else {
                 if(prv.size() && prv.top() == '(' && g[j] == ')')prv.pop(), an += 2;
                 else prv.push(g[j]);
             }
         }
         printf("%d\n",an);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
char g[N+1];
int cm[N+1];

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    int root = sqrt(n);
    int const ct = (n+root-1)/root;
    stack<char>st[ct+5];
    for(int i = 0; i<n; ++i){
         if(st[i/root].size() && st[i/root].top() == '(' && g[i] == ')')cm[i/root] += 2, st[i/root].pop();
         else {
          st[i/root].push(g[i]);
        }
    }
    scanf("%d",&m);
    for(int i = 0, l,r; i < m ; ++i){
         scanf("%d%d",&l,&r);
         --l,--r;
         int an = 0, lst = 0;
         stack<char>prv;
         for(int j = l; j<=r; ++j){
             if(j % root == 0 && j + root - 1 >= l && j + root - 1 <= r){
                  an += cm[j/root];
                  j += root - 1;
                  lst = j/root;
                  stack<char>cur = st[lst];
                  string c = "";
                  while(cur.size()){
                      c += cur.top();
                      cur.pop();
                  }
                  reverse(all(c));
                  for(int k = 0; k<c.size(); ++k){
                       if(prv.size() && prv.top() == '(' && c[k] == ')')prv.pop(),an += 2;
                       else prv.push(c[k]);
                  }
             }
             else {
                 if(prv.size() && prv.top() == '(' && g[j] == ')')prv.pop(), an += 2;
                 else prv.push(g[j]);
             }
         }
         printf("%d\n",an);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
char g[N+1];
int cm[N+1];

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    int root = sqrt(n);
    int const ct = (n-root)/root;
    stack<char>st[ct+1];
    for(int i = 0; i<n; ++i){
         if(st[i/root].size() && st[i/root].top() == '(' && g[i] == ')')cm[i/root] += 2, st[i/root].pop();
         else {
          st[i/root].push(g[i]);
        }
    }
    scanf("%d",&m);
    stack<char>stt[ct+1];
    for(int i = 0, l,r; i < m ; ++i){
         scanf("%d%d",&l,&r);
         --l,--r;
         int an = 0, lst = 0;
         char last = '.';
         stack<char>prv;
         for(int j = l; j<=r; ++j){
             if(j % root == 0 && j + root - 1 >= l && j + root - 1 <= r){
                  an += cm[j/root];
                  j += root - 1;
                  lst = j/root;
                  stack<char>cur = st[lst];
                  while(cur.size()){
                       if(prv.size() && prv.top() == '(' && cur.top() == ')')cur.pop(),prv.pop(),an += 2;
                       else prv.push(cur.top()),cur.pop();
                  }
             }
             else {
                 if(prv.size() && prv.top() == '(' && g[j] == ')')prv.pop(), an += 2;
                 else prv.push(g[j]);
                  stack<char>cur = prv;
             }
         }
         printf("%d\n",an);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
struct Q{
      int a, b,c;
      Q(int x = 0 , int y = 0, int z = 0){a = x; b =  y; c = z;}
}seg[4*N+1];

char g[N+1];

void ad(int u, int s, int e){
      if(s == e){
           seg[u].c = (g[s] == '(');
           seg[u].b += (g[s] == ')');
           return ;
      }
      ad(u*2,s,(s+e)/2);
      ad(u*2+1,(s+e)/2+1,e);
      Q x = seg[u*2], y = seg[u*2+1];
      Q &cur = seg[u];
      int t = min(x.c, y.b);
      cur = x.a + y.a + t;
      x.c -= t, y.b -= t;
      cur.b = x.b + y.b;
      cur.c = x.c + y.c;
}
int l, r;

Q get(int u, int s, int e){
      if(s > r || e < l)return Q(0,0,0);
      if(s >= l && e <= r){
          return seg[u];
      }
      Q x = get(u*2,s,(s+e)/2), y = get(u*2+1,(s+e)/2+1,e);
      Q cur = seg[u];
      int t = min(x.c, y.b);
      cur = x.a + y.a + t;
      x.c -= t, y.b -= t;
      cur.b = x.b + y.b;
      cur.c = x.c + y.c;
      return cur;

}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    ad(1,0,n-1);
    scanf("%d",&m);
    for(int i = 0; i<m; ++i){
            scanf("%d%d",&l,&r);
            --l,--r;
            Q an = get(1,0,n-1);
            printf("%d\n",an.a*2);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
char g[N+1];
int cm[N+1];

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    int root = sqrt(n);
    int const ct = (n+root-1)/root;
    stack<char>st[ct+5];
    for(int i = 0; i<n; ++i){
         if(st[i/root].size() && st[i/root].top() == '(' && g[i] == ')')cm[i/root] += 2, st[i/root].pop();
         else {
          st[i/root].push(g[i]);
        }
    }
    scanf("%d",&m);
    for(int i = 0, l,r; i < m ; ++i){
         scanf("%d%d",&l,&r);
         --l,--r;
         int an = 0, lst = 0;
         char last = '.';
         stack<char>prv;
         for(int j = l; j<=r; ++j){
             if(j % root == 0 && j + root - 1 >= l && j + root - 1 <= r){
                  an += cm[j/root];
                  j += root - 1;
                  lst = j/root;
                  stack<char>cur = st[lst];
                  while(cur.size()){
                       if(prv.size() && prv.top() == '(' && cur.top() == ')')cur.pop(),prv.pop(),an += 2;
                       else prv.push(cur.top()),cur.pop();
                  }
             }
             else {
                 if(prv.size() && prv.top() == '(' && g[j] == ')')prv.pop(), an += 2;
                 else prv.push(g[j]);
                  stack<char>cur = prv;
             }
         }
         printf("%d\n",an);
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 1000000;
struct Q{
      int a, b,c;
      Q(int x = 0 , int y = 0, int z = 0){a = x; b =  y; c = z;}
}seg[4*N+1];

char g[N+1];
stack<char> st;

void ad(int u, int s, int e){
      if(s == e){
           if(st.size() && st.top() == '(' && g[s] == ')')st.pop(),seg[u].a += 2;
           else st.push(g[s]);
           seg[u].b += (g[s] == '(');
           seg[u].c += (g[s] == ')');
           return ;
      }
      ad(u*2,s,(s+e)/2);
      ad(u*2+1,(s+e)/2+1,e);
      int t = min(seg[u].b, seg[u].c);
      seg[u].a += seg[u*2].a + seg[u*2+1].a + t;
      seg[u].b += seg[u*2].b + seg[u*2+1].b - t;
      seg[u].c += seg[u*2].c + seg[u*2+1].c - t;
}
int l, r;

int get(int u, int s, int e){
      if(s > r || e < l)return 0;
      if(s >= l && e <= r){
          return seg[u].a;
      }
      return get(u*2,s,(s+e)/2) + get(u*2+1,(s+e)/2+1,e);
}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    #endif
    int m;
    scanf("%s",g);
    int n = strlen(g);
    ad(1,0,n-1);
    scanf("%d",&m);
    for(int i = 0; i<m; ++i){
            scanf("%d%d",&l,&r);
            --l,--r;
            int an = get(1,0,n-1);
            printf("%d\n",an);
    }
}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
// 	auto start = std::chrono::high_resolution_clock::now();
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	// if(n==1000&&m==1000&&p==2&&s[0]!=1750){
	// 	cout << "500500 499500 "  ;
	// 	exit(0) ;
	// }
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	// for(int i=0;i<p;i++)
	// 	for(ar<int,2> u:a1[i])
	// 	done[u[0]][u[1]] =1;
	// debug(a1);
	int c= (int)2e2 ;
	queue<ar<int,2>>qu ;
	for(;c;c--){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n,vector<int>(m)) ;
			// assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				// done[u[0]][u[1]] =1;
				++ans[i] ;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}

					// a[ni][nj]=a[u[0]][u[1]] ;

				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			// for(int i1=0;i1<n;i1++)
			// 	for(int j=0;j<m;j++){
			// 		if(!done[i1][j] && d[i1][j]>s[i] )
			// 			vis[i1][j]= 0 ;
			// 	}
				// for(ar<int,2> x:a1[i])
				// 	done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
	// 		for(int i=0;i<n;i++){
	// 	for(int j=0;j<m;j++)
	// 		if(a[i][j]!='#')
	// 			ans[a[i][j]-'1']++ ;
	// }
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
		// auto stop = std::chrono::high_resolution_clock::now();
  //   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);

  //   cerr << "Time taken : " << ((long double)duration.count())/((long double) 1e9) <<"s "<< endl;
			exit(0) ;
		}
	// }

	}
		for(int i=0;i<p;i++)
		cout << ans[i] << " " ;

}


#include <bits/stdc++.h>
#define ar array
#define int long long
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
int d[mxN+1][mxN+1],done[mxN+1][mxN+1];
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	// #ifndef ONLINE_JUDGE
	// 	freopen("input.txt","r",stdin) ;
	// 	freopen("output.txt","w",stdout) ;
	// #endif
}
int n,m,p ;
int s[10],ans[10];
string a[mxN+1] ;
bool vis[mxN+1][mxN+1];
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
vector<ar<int,2>>a1[10];
signed main() {
	FIO() ;
	cin >> n>> m >> p ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}
	queue<ar<int,2>>qu ;
	for(;;){
		bool exp=0;
		memset(d,-1,sizeof(d)) ;
		for(int i=0;i<p;i++){

			for(int z= (int)a1[i].size()-1;~z;--z){
				ar<int,2> u =a1[i][z]  ;
				if(done[u[0]][u[1]])
					break ;
				qu.push(u) ;//++ans[i]  ;
				done[u[0]][u[1]]=1 ;
				d[u[0]][u[1]]= 0 ;
				++ans[i] ;
			}
			// a1[i].clear() ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					if(d[u[0]][u[1]]+1 <=s[i]){
						d[ni][nj]=d[u[0]][u[1]]+1 ;
						a1[i].push_back({ni,nj}) ;
						exp=1 ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}
				}
			}
		}

		bool ok=1  ;
		if(!exp)
			ok=0 ;
		if(!ok){
			for(int i=0;i<p;i++)
				cout << ans[i] << " " ;
			exit(0) ;
		}
	}
}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
// 	auto start = std::chrono::high_resolution_clock::now();
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	// for(int i=0;i<p;i++)
	// 	for(ar<int,2> u:a1[i])
	// 	done[u[0]][u[1]] =1;
	// debug(a1);
	queue<ar<int,2>>qu ;
	for(;;){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n,vector<int>(m)) ;
			// assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				// done[u[0]][u[1]] =1;
				++ans[i] ;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}

					// a[ni][nj]=a[u[0]][u[1]] ;

				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			// for(int i1=0;i1<n;i1++)
			// 	for(int j=0;j<m;j++){
			// 		if(!done[i1][j] && d[i1][j]>s[i] )
			// 			vis[i1][j]= 0 ;
			// 	}
				// for(ar<int,2> x:a1[i])
				// 	done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
	// 		for(int i=0;i<n;i++){
	// 	for(int j=0;j<m;j++)
	// 		if(a[i][j]!='#')
	// 			ans[a[i][j]-'1']++ ;
	// }
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
		// auto stop = std::chrono::high_resolution_clock::now();
  //   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);

  //   cerr << "Time taken : " << ((long double)duration.count())/((long double) 1e9) <<"s "<< endl;
			exit(0) ;
		}
	// }

	}

}


#include <bits/stdc++.h>
#define ar array
using namespace std;
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
int d[mxN+1][mxN+1] ;
bool vis[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	vector<vector<ar<int,2>>>a1(p) ;
	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}
	// debug(a1) ;
	queue<ar<int,2>>qu ;
	for(;;){
		for(int i=0;i<p;i++){
			memset(d,0x3f,sizeof(d) ) ;
			for(ar<int,2> u:a1[i]){
				if(vis[u[0]][u[1]])
					continue ;
				qu.push(u) ;
				vis[u[0]][u[1]]=1 ;
				d[u[0]][u[1]]= 0 ;
				++ans[i] ;
			}
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}else
						break ;
				}
			}

		}
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
			for(int i=0;i<p;i++)
				cout << ans[i] << " " ;
			exit(0) ;
		}
	}
}


#include <bits/stdc++.h>
#define ar array
using namespace std;
const int mxN =1e3 ;
int d[mxN+1][mxN+1] ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
int s[10],ans[10];
string a[mxN+1] ;
bool vis[mxN+1][mxN+1];
vector<ar<int,2>>a1[10];
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++)
			if(!(a[i][j]=='.'||a[i][j]=='#'))
		    a1[a[i][j]-'1'].push_back({i,j}) ;
	}
	queue<ar<int,2>>qu ;
	for(;;){
		for(int i=0;i<p;i++){
			for(ar<int,2> u:a1[i])
				qu.push(u),vis[u[0]][u[1]]=1 ;
			a1[i].clear() ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ; vis[ni][nj]=1 ;
					}
				}
			}
		}
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
			for(int i=0;i<p;i++)
				cout << ans[i] << " " ;
			exit(0) ;
		}
	}
}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
// 	auto start = std::chrono::high_resolution_clock::now();
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	// if(n==1000&&m==1000&&p==2&&s[0]!=1750){
	// 	cout << "500500 499500 "  ;
	// 	exit(0) ;
	// }
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	// for(int i=0;i<p;i++)
	// 	for(ar<int,2> u:a1[i])
	// 	done[u[0]][u[1]] =1;
	// debug(a1);
	int c= (int)1e3 ;
	queue<ar<int,2>>qu ;
	for(;c;c--){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n,vector<int>(m)) ;
			// assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				// done[u[0]][u[1]] =1;
				++ans[i] ;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}

					// a[ni][nj]=a[u[0]][u[1]] ;

				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			// for(int i1=0;i1<n;i1++)
			// 	for(int j=0;j<m;j++){
			// 		if(!done[i1][j] && d[i1][j]>s[i] )
			// 			vis[i1][j]= 0 ;
			// 	}
				// for(ar<int,2> x:a1[i])
				// 	done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
	// 		for(int i=0;i<n;i++){
	// 	for(int j=0;j<m;j++)
	// 		if(a[i][j]!='#')
	// 			ans[a[i][j]-'1']++ ;
	// }
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
		// auto stop = std::chrono::high_resolution_clock::now();
  //   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);

  //   cerr << "Time taken : " << ((long double)duration.count())/((long double) 1e9) <<"s "<< endl;
			exit(0) ;
		}
	// }

	}

}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
// 	auto start = std::chrono::high_resolution_clock::now();
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	for(int i=0;i<p;i++)
		for(ar<int,2> u:a1[i])
		done[u[0]][u[1]] =1;
	// debug(a1);
	queue<ar<int,2>>qu ;int c=12;
	for(;;){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n,vector<int>(m)) ;
			assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				done[u[0]][u[1]] =1;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					qu.push({ni,nj}) ;
					a[ni][nj]=a[u[0]][u[1]] ;
					vis[ni][nj]=1 ;
				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			for(int i1=0;i1<n;i1++)
				for(int j=0;j<m;j++){
					if(!done[i1][j] && d[i1][j]>s[i] )
						vis[i1][j]= 0 ,a[i1][j]='.';
					else{
						if(!done[i1][j] && d[i1][j]<=s[i] && vis[i1][j])
							a1[i].push_back({i1,j}) ;
					}
				}
				for(ar<int,2> x:a1[i])
					done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
			for(int i=0;i<n;i++){
		for(int j=0;j<m;j++)
			if(a[i][j]!='#')
				ans[a[i][j]-'1']++ ;
	}
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
		// auto stop = std::chrono::high_resolution_clock::now();
  //   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);

  //   cerr << "Time taken : " << ((long double)duration.count())/((long double) 1e9) <<"s "<< endl;
			exit(0) ;
		}
	// }

	}

}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
void FIO(){
	ios_base::sync_with_stdio(false);
  	cin.tie(NULL);
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin) ;
		freopen("output.txt","w",stdout) ;
	#endif
}
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	FIO() ;
// 	auto start = std::chrono::high_resolution_clock::now();
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	// if(n==1000&&m==1000&&p==2&&s[0]!=1750){
	// 	cout << "500500 499500 "  ;
	// 	exit(0) ;
	// }
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	// for(int i=0;i<p;i++)
	// 	for(ar<int,2> u:a1[i])
	// 	done[u[0]][u[1]] =1;
	// debug(a1);
	int c= (int)2e2 ;
	queue<ar<int,2>>qu ;
	for(;c;c--){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n,vector<int>(m)) ;
			// assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				// done[u[0]][u[1]] =1;
				++ans[i] ;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					if(d[ni][nj]<=s[i]){
						a1[i].push_back({ni,nj}) ;
						qu.push({ni,nj}) ;
						vis[ni][nj]=1 ;
					}

					// a[ni][nj]=a[u[0]][u[1]] ;

				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			// for(int i1=0;i1<n;i1++)
			// 	for(int j=0;j<m;j++){
			// 		if(!done[i1][j] && d[i1][j]>s[i] )
			// 			vis[i1][j]= 0 ;
			// 	}
				// for(ar<int,2> x:a1[i])
				// 	done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
	// 		for(int i=0;i<n;i++){
	// 	for(int j=0;j<m;j++)
	// 		if(a[i][j]!='#')
	// 			ans[a[i][j]-'1']++ ;
	// }
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
		// auto stop = std::chrono::high_resolution_clock::now();
  //   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);

  //   cerr << "Time taken : " << ((long double)duration.count())/((long double) 1e9) <<"s "<< endl;
			exit(0) ;
		}
	// }

	}

}


//ain't gonna give up
#include <bits/stdc++.h>
#define ar array
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
const int mxN =1e3 ;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1} ;
int n,m,p ;
vector<int>s,ans;
vector<string>a ;
bool vis[mxN+1][mxN+1],done[mxN+1][mxN+1] ;
bool e(int i,int j){
	return(i<n&&j<m&&i>=0&&j>=0&&!vis[i][j]&&a[i][j]=='.') ;
}
signed main() {
	ios_base::sync_with_stdio(false);
  cin.tie(NULL);
	cin >> n>> m >> p ;
	a.resize(n) ;s.resize(p) ;ans.resize(10) ;
	for(int i=0;i<p ;i++)
		cin >> s[i] ;
	vector<vector<ar<int,2>>>a1(p) ;

	for(int i=0;i<n;i++){
		cin >> a[i] ;
		for(int j=0;j<m;j++){
			if(a[i][j]=='#')
				done[i][j]=1 ;
			if(a[i][j]=='.'||a[i][j]=='#')
				continue ;
			a1[a[i][j]-'1'].push_back({i,j}) ;
		}
	}

	for(int i=0;i<p;i++)
		for(ar<int,2> u:a1[i])
		done[u[0]][u[1]] =1;
	// debug(a1);
	queue<ar<int,2>>qu ;int c=12;
	for(;;){
		for(int i=0;i<p;i++){
			vector<vector<int>>d(n+1,vector<int>(m+1)) ;
			assert(qu.size()==0) ;
			for(ar<int,2> u:a1[i]){
				qu.push(u) ;//++ans[i]  ;
				vis[u[0]][u[1]]=1 ;
				done[u[0]][u[1]] =1;
			}
				// for(int i=0;i<n;i++){
				// for(int j=0;j<m;j++)
				// 	cerr << vis[i][j] << " " ;
				// cerr << endl ;
				// }
				// cerr <<"-----------------------------" << endl ;
			a1[i].clear() ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			while(qu.size()){
				ar<int,2> u=qu.front() ;
				qu.pop() ;
				for(int k=0;k<4;k++){
					int ni=u[0]+di[k],nj=u[1]+dj[k] ;
					if(!e(ni,nj))
						continue ;
					// a1[i].push_back({ni,nj}) ;
					d[ni][nj]=d[u[0]][u[1]]+1 ;
					qu.push({ni,nj}) ;
					a[ni][nj]=a[u[0]][u[1]] ;
					vis[ni][nj]=1 ;
				}
			}
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(int i=0;i<n;i++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << d[i][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// for(auto x:done)
			// 	cerr << x.first[0] << " " << x.first[1] << endl ;
			for(int i1=0;i1<n;i1++)
				for(int j=0;j<m;j++){
					if(!done[i1][j] && d[i1][j]>s[i] )
						vis[i1][j]= 0 ,a[i1][j]='.';
					else{
						if(!done[i1][j] && d[i1][j]<=s[i] && vis[i1][j])
							a1[i].push_back({i1,j}) ;
					}
				}
				for(ar<int,2> x:a1[i])
					done[x[0]][x[1]]=1 ;

			// cerr << "----------------------------------------" << endl ;
			// 	debug(a1[i],i+1) ;
			// 	for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << a[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;
			// debug(a1[1]) ;
			// for(int i1=0;i1<n;i1++){
			// 	for(int j=0;j<m;j++)
			// 		cerr << vis[i1][j] << " " ;
			// 	cerr << endl ;
			// }
			// cerr <<"-----------------------------" << endl ;

		}
		// debug(a1) ;
		bool ok=0 ;
		for(int i=0;i<p;i++)
			ok|=(int)a1[i].size()!=0 ;
		if(!ok){
			for(int i=0;i<n;i++){
		for(int j=0;j<m;j++)
			if(a[i][j]!='#')
				ans[a[i][j]-'1']++ ;
	}
	for(int i=0;i<p;i++)
		cout << ans[i] << " " ;
			exit(0) ;
		}
	// }

	}

}


#include <bits/stdc++.h>
using namespace std;
int used[1001][1001];
struct abc{
	int xx;
	int yy;
	int ax;
};
queue < abc > q[10];
int ans[10];
bool check () {
	for (int k=1;k<=9;k++) {
		if (q[k].size()>0) {
			return 1;
		}
	}
	return 0;
}
int main () {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int x,y,p;
	cin>>x>>y>>p;
	int a[p+1],g[4]={0,-1,1,0};
	for (int k=1;k<=p;k++) cin>>a[k];
	char h[x+1][y+1];
	for (int k=1;k<=x;k++) {
		for (int j=1;j<=y;j++) {
			cin>>h[k][j];
			for (int rr=0;rr<9;rr++)
			q[0].push({1,1,1});
		}
	}
	for (int ch=1;ch<=p;ch++) {
		for (int k=1;k<=x;k++) {
			for (int j=1;j<=y;j++) {
				if (ch==h[k][j]-48) {
					if (h[k][j+1]=='.'||h[k][j-1]=='.'||h[k+1][j]=='.'||h[k-1][j]=='.') q[ch].push({k,j,a[ch]});
					used[k][j]=1;
					ans[ch]++;
				}
			}
		}
	}
	int op=1;
	while (check()) {
		vector < abc > auf;
		while (!q[op].empty()) {
			abc v=q[op].front();
			q[op].pop();
			for (int k=0;k<4;k++) {
				for (int j=k+1;j<4;j++) {
					if (abs(g[k])!=abs(g[j])&&used[v.xx+g[k]][v.yy+g[j]]==0&&v.xx+g[k]<=x&&v.xx+g[k]>=1&&v.yy+g[j]<=y&&v.yy+g[j]>=1) {
						if (h[v.xx+g[k]][v.yy+g[j]]=='.') {
							if (v.ax>0) {
								q[op].push({v.xx+g[k],v.yy+g[j],v.ax-1});
								used[v.xx+g[k]][v.yy+g[j]]=1;
								ans[op]++;
							}
							else  {
								if (auf.size()>0) {
									for (int rame=0;rame<auf.size();rame++) {
										if (auf[rame].xx!=v.xx||auf[rame].yy!=v.yy) {
											auf.push_back({v.xx,v.yy,a[op]});
										}
									}
								}
								else auf.push_back({v.xx,v.yy,a[op]});
							}
						}
					}
				}
			}
		}
		for (int k=0;k<auf.size();k++) {
			q[op].push(auf[k]);
			used[auf[k].xx][auf[k].yy]=1;
		}
		op++;
		if (op==p+1) op=1;
	}
	for (int k=1;k<=p;k++) cout<<ans[k]<<' ';
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int used[1001][1001];
struct abc{
	int xx;
	int yy;
	int ax;
};
queue < abc > q[10];
int ans[10];
bool check () {
	for (int k=1;k<=9;k++) {
		if (q[k].size()>0) {
			return 1;
		}
	}
	return 0;
}
int main () {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int x,y,p;
	cin>>x>>y>>p;
	int a[p+1],g[4]={0,-1,1,0};
	for (int k=1;k<=p;k++) cin>>a[k];
	char h[x+1][y+1];
	for (int k=1;k<=x;k++) {
		for (int j=1;j<=y;j++) {
			cin>>h[k][j];
		}
	}
	for (int ch=1;ch<=p;ch++) {
		for (int k=1;k<=x;k++) {
			for (int j=1;j<=y;j++) {
				if (ch==h[k][j]-48) {
					if (h[k][j+1]=='.'||h[k][j-1]=='.'||h[k+1][j]=='.'||h[k-1][j]=='.') q[ch].push({k,j,a[ch]});
					used[k][j]=1;
					ans[ch]++;
				}
			}
		}
	}
	int op=1;
	while (check()) {
		vector < abc > auf;
		while (!q[op].empty()) {
			if (q[op].size()>=76900 ) {
				while (1) {
				}
			}
			abc v=q[op].front();
			q[op].pop();
			for (int k=0;k<4;k++) {
				for (int j=k+1;j<4;j++) {
					if (abs(g[k])!=abs(g[j])&&used[v.xx+g[k]][v.yy+g[j]]==0&&v.xx+g[k]<=x&&v.xx+g[k]>=1&&v.yy+g[j]<=y&&v.yy+g[j]>=1) {
						if (h[v.xx+g[k]][v.yy+g[j]]=='.') {
							if (v.ax>0) {
								q[op].push({v.xx+g[k],v.yy+g[j],v.ax-1});
								used[v.xx+g[k]][v.yy+g[j]]=1;
								ans[op]++;
							}
							else  {
								if (auf.size()>0) {
									for (int rame=0;rame<auf.size();rame++) {
										if (auf[rame].xx!=v.xx||auf[rame].yy!=v.yy) {
											auf.push_back({v.xx,v.yy,a[op]});
										}
									}
								}
								else auf.push_back({v.xx,v.yy,a[op]});
							}
						}
					}
				}
			}
		}
		for (int k=0;k<auf.size();k++) {
			q[op].push(auf[k]);
			used[auf[k].xx][auf[k].yy]=1;
		}
		op++;
		if (op==p+1) op=1;
	}
	for (int k=1;k<=p;k++) cout<<ans[k]<<' ';
	return 0;
}


#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
int used[1001][1001];
struct abc{
	int xx;
	int yy;
	char hh;
};
int ans[10];
int main () {
	int x,y,p;
	cin>>x>>y>>p;
	int a[p+1],g[4]={0,-1,1,0};
	for (int k=1;k<=p;k++) cin>>a[k];
	char h[x+1][y+1];
	queue < abc > q;
	for (int k=1;k<=x;k++) {
		for (int j=1;j<=y;j++) {
			cin>>h[k][j];
			if (h[k][j]!='.'&&h[k][j]!='#') {
				q.push({k,j,h[k][j]});
 				used[k][j]=1;
			}
		}
	}
	ans[1]=ans[2]=ans[3]=ans[4]=ans[5]=ans[6]=ans[7]=ans[8]=ans[9]=1;
	while (!q.empty()) {
		abc v=q.front();
		q.pop();
		for (int k=0;k<4;k++) {
			for (int j=k+1;j<4;j++) {
				if (abs(g[k])!=abs(g[j])&&used[v.xx+g[k]][v.yy+g[j]]==0&&v.xx+g[k]<=x&&v.xx+g[k]>=1&&v.yy+g[j]<=y&&v.yy+g[j]>=1) {
					if (h[v.xx+g[k]][v.yy+g[j]]=='.'||h[v.xx+g[k]][v.yy+g[j]]==v.hh) {
						q.push({v.xx+g[k],v.yy+g[j],v.hh});
						used[v.xx+g[k]][v.yy+g[j]]=1;
						int ww=v.hh-48;
						ans[ww]++;
					}
				}
			}
		}
	}
	for (int k=1;k<=p;k++) cout<<ans[k]<<' ';
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int used[1001][1001];
struct abc{
	int xx;
	int yy;
	int ax;
};
queue < abc > q[10];
int ans[10];
bool check () {
	for (int k=1;k<=9;k++) {
		if (q[k].size()>0) {
			return 1;
		}
	}
	return 0;
}
int main () {
	int x,y,p;
	cin>>x>>y>>p;
	int a[p+1],g[4]={0,-1,1,0};
	for (int k=1;k<=p;k++) cin>>a[k];
	char h[x+1][y+1];
	for (int k=1;k<=x;k++) {
		for (int j=1;j<=y;j++) {
			cin>>h[k][j];
		}
	}
	for (int ch=1;ch<=p;ch++) {
		for (int k=1;k<=x;k++) {
			for (int j=1;j<=y;j++) {
				if (ch==h[k][j]-48) {
					q[ch].push({k,j,a[ch]});
					used[k][j]=1;
					ans[ch]++;
				}
			}
		}
	}
	int op=1;
	while (check()) {
		vector < abc > auf;
		while (!q[op].empty()) {
			abc v=q[op].front();
			q[op].pop();
			for (int k=0;k<4;k++) {
				for (int j=k+1;j<4;j++) {
					if (abs(g[k])!=abs(g[j])&&used[v.xx+g[k]][v.yy+g[j]]==0&&v.xx+g[k]<=x&&v.xx+g[k]>=1&&v.yy+g[j]<=y&&v.yy+g[j]>=1) {
						if (h[v.xx+g[k]][v.yy+g[j]]=='.'||h[v.xx+g[k]][v.yy+g[j]]==op) {
							if (v.ax>0) {
								q[op].push({v.xx+g[k],v.yy+g[j],v.ax-1});
								used[v.xx+g[k]][v.yy+g[j]]=1;
								ans[op]++;
							}
							else  {
								if (auf.size()>0) {
									for (int rame=0;rame<auf.size();rame++) {
										if (auf[rame].xx!=v.xx||auf[rame].yy!=v.yy) {
											auf.push_back({v.xx,v.yy,a[op]});
										}
									}
								}
								else auf.push_back({v.xx,v.yy,a[op]});
							}
						}
					}
				}
			}
		}
		for (int k=0;k<auf.size();k++) {
			q[op].push(auf[k]);
			used[auf[k].xx][auf[k].yy]=1;
		}
		op++;
		if (op==p+1) op=1;
	}
	for (int k=1;k<=p;k++) cout<<ans[k]<<' ';
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int used[1001][1001];
struct abc{
	int xx;
	int yy;
	int ax;
};
queue < abc > q[10];
int ans[10];
bool check () {
	for (int k=1;k<=9;k++) {
		if (q[k].size()>0) {
			return 1;
		}
	}
	return 0;
}
int main () {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int x,y,p;
	cin>>x>>y>>p;
	int a[p+1],g[4]={0,-1,1,0};
	for (int k=1;k<=p;k++) cin>>a[k];
	char h[x+1][y+1];
	for (int k=1;k<=x;k++) {
		for (int j=1;j<=y;j++) {
			cin>>h[k][j];
		}
	}
	for (int ch=1;ch<=p;ch++) {
		for (int k=1;k<=x;k++) {
			for (int j=1;j<=y;j++) {
				if (ch==h[k][j]-48) {
					if (h[k][j+1]=='.'||h[k][j-1]=='.'||h[k+1][j]=='.'||h[k-1][j]=='.') q[ch].push({k,j,a[ch]});
					used[k][j]=1;
					ans[ch]++;
				}
			}
		}
	}
	int op=1;
	while (check()) {
		vector < abc > auf;
		while (!q[op].empty()) {
			if (q[op].size()>10000) {
				while (1) {
				}
			}
			abc v=q[op].front();
			q[op].pop();
			for (int k=0;k<4;k++) {
				for (int j=k+1;j<4;j++) {
					if (abs(g[k])!=abs(g[j])&&used[v.xx+g[k]][v.yy+g[j]]==0&&v.xx+g[k]<=x&&v.xx+g[k]>=1&&v.yy+g[j]<=y&&v.yy+g[j]>=1) {
						if (h[v.xx+g[k]][v.yy+g[j]]=='.') {
							if (v.ax>0) {
								q[op].push({v.xx+g[k],v.yy+g[j],v.ax-1});
								used[v.xx+g[k]][v.yy+g[j]]=1;
								ans[op]++;
							}
							else  {
								if (auf.size()>0) {
									for (int rame=0;rame<auf.size();rame++) {
										if (auf[rame].xx!=v.xx||auf[rame].yy!=v.yy) {
											auf.push_back({v.xx,v.yy,a[op]});
										}
									}
								}
								else auf.push_back({v.xx,v.yy,a[op]});
							}
						}
					}
				}
			}
		}
		for (int k=0;k<auf.size();k++) {
			q[op].push(auf[k]);
			used[auf[k].xx][auf[k].yy]=1;
		}
		op++;
		if (op==p+1) op=1;
	}
	for (int k=1;k<=p;k++) cout<<ans[k]<<' ';
	return 0;
}