#include<bits/stdc++.h>
#include<bits/extc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
using namespace __gnu_pbds;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t){
	while(*sdbg != ',') { cerr<<*sdbg++; } cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef DEBUG
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr<<#x<<": "; for(auto i:x) cerr<<i<<" "; cerr<<endl;}}
#define debugr(l, r, x) {{cerr<<#x<<": "; for(int i=l;i<=r;i++) cerr<<x<<" "; cerr<<endl;}}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define debugr(l, r, x)
#define cerr while(0) cerr
#endif
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define priority_queue std::priority_queue
#define F first
#define S second
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

char a[1005][1005];
bool vis[3005];
vi adj[3005];
void dfs(int x){
	vis[x]=true;
	for(int y:adj[x]){
		if(!vis[y]) dfs(y);
	}
}

signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int h, w;
	cin>>h>>w;
	set<int> row, col;
	auto add=[&](int x, int y){
		adj[x].push_back(h+y);
		adj[h+y].push_back(x);
		row.insert(x);
		col.insert(h+y);
	};
	add(1, 1);
	add(1, w);
	add(h, 1);
	add(h, w);
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			cin>>a[i][j];
			if(a[i][j]=='#'){
				add(i, j);
			}
		}
	}
	int ccs=0;
	for(int i:row){
		if(!vis[i]){
			dfs(i);
			ccs++;
		}
	}
	for(int i:col){
		if(!vis[i]){
			dfs(i);
			ccs++;
		}
	}
	debug(row.size(), col.size());
	cout<<ccs+min(h-row.size(), w-col.size())-1<<endl;
}
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
  
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
  
using namespace __gnu_pbds;

int n;
vector<int> adj[200005];
ordered_set ins[200005], outs[200005];
int in[200005], out[200005], dis[200005];
int t=0;


void dfs(int u,int p)
{
	in[u] = ++t;
	for(auto x:adj[u])
	{
		if(x!=p) dis[x]=dis[u]+1, dfs(x,u);
	}
	out[u]=++t;
}




int main()
{
	cin>>n;
	for(int i=2;i<=n;i++)
	{
		int x;cin>>x;
		adj[i].push_back(x);
		adj[x].push_back(i);
	}

	dfs(1,0);
	for(int i=1;i<=n;i++)ins[dis[i]].insert(in[i]), outs[dis[i]].insert(out[i]);

	int q;
	cin>>q;
	while(q--)
	{
		int u,d;cin>>u>>d;
		int ans=ins[d].order_of_key(out[u])-ins[d].order_of_key(in[u]);
		
		cout<<ans<<endl;
	}
}



