#include <bits/stdc++.h>

using namespace std;


typedef long long ll;

const int M = 1e9+7 ;

const ll INF = 1e18 ;




int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int N; 
    cin  >>  N;

    vector<vector<int>> A(N, vector<int>(2));

    for (int i = 0; i < N; ++i) {
        cin >> A[i][0] >> A[i][1];
    }

    auto comp = [&](vector<int>& a, vector<int>& b) {
        return a[0] + a[1] < b[0] + b[1];
    };

    sort(A.begin(), A.end(), comp);

    vector<vector<ll>> dp (N+1 , vector<ll> (N+1, INF)); 

    



    for(int i = 0 ; i <= N; ++i){

        dp[i][0] = 0 ;
    }

    for(int i = 1 ; i <= N; ++i){
        for(int j = 1 ; j <= i ; ++j ){
            dp[i][j] = dp[i-1][j]; 
            if (A[i-1][0] >= dp[i-1][j-1]){
                dp[i][j] = min(dp[i][j] , dp[i-1][j-1] + A[i-1][1]);
            }
        }
    }


    for(int j = N ;  j >= 0; --j){
        if (dp[N][j] != INF){
            cout <<  j << "\n"; 
            break; 
        }
    }

    



    
  
    return 0;
}


#include <bits/stdc++.h>
#define int long long
#define mod (int)(1e9+7)
#define inf (int)(3e18)
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,n) for(int i=1;i<n;i++)
#define P std::pair<int,int>
#define PiP std::pair<int,std::pair<int,int>>
#define all(v) v.begin(),v.end()
#define mkp std::make_pair
#define prique(T) std::priority_queue<T,vector<T>,greater<T>>
using namespace std;
template<class T> inline void chmax(T& a, T b) { a = std::max(a, b); }
template<class T> inline void chmin(T& a, T b) { a = std::min(a, b); }

bool prime(int x) {
	for (int i = 2; i * i <= x; i++) {
		if (x % i == 0)return false;
	}
	return x != 1;
}
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x % y);
}
int lcm(int x, int y) {
	return x / gcd(x, y) * y;
}
int kai(int x, int y) {
	int res = 1;
	for (int i = x - y + 1; i <= x; i++) {
		res *= i; res %= mod;
	}
	return res;
}
int mod_pow(int x, int y, int m) {
	int res = 1;
	while (y > 0) {
		if (y & 1) {
			res = res * x % m;
		}
		x = x * x % m;
		y >>= 1;
	}
	return res;
}
int comb(int x, int y) {
	if (y > x)return 0;
	return kai(x, y) * mod_pow(kai(y, y), mod - 2, mod) % mod;
}
int get_rand(int MIN, int MAX) {
	std::random_device rnd;
	std::mt19937 mt32(rnd());
	std::uniform_int_distribution<int>engine(MIN, MAX);
	return engine(mt32);
}
/*--------Library Zone!--------*/

int n, q;
string s;
int summ[1000005];
signed main() {
	cin >> n >> s >> q;
	rep(i, n) {
		if (s[i] == 'M')summ[i]++;
		summ[i + 1] = summ[i];
	}
	while (q--) {
		int k; cin >> k;
		int ans = 0;
		int d = 0, dm = 0;
		rep(i, n) {
			if (s[i] == 'D')d++;
			else if (s[i] == 'M')dm += d;
			else if (s[i] == 'C')ans += dm;
			if (i >= k - 1 && s[i - k + 1] == 'D') {
				d--;
				dm -= summ[i] - (i >= k ? summ[i - k] : 0);
			}
		}
		cout << ans << endl;
	}
}
