#include using namespace std; template istream& operator >> (istream& is, vector& vec) { for(T& x : vec) is >> x; return is; } int main(){ ios::sync_with_stdio(false); cin.tie(0); int m, Q, k, x; cin >> m; vector a(28), b(28); vector> tb1(15), tb2(15); cin >> a >> b; for(int S = 0; S < (1 << 14); S++){ int s1 = 0, s2 = 0, c = __builtin_popcount(S); for(int i = 0; i < 14; i++){ if(S >> i & 1){ s1 = (s1 + a[i]) % m; s2 = (s2 + a[i + 14]) % m; }else{ s1 = (s1 + b[i]) % m; s2 = (s2 + b[i + 14]) % m; } } tb1[c].emplace_back(s1); tb2[c].emplace_back(s2); } for(int i = 0; i < 15; i++){ sort(tb1[i].begin(), tb1[i].end()); sort(tb2[i].begin(), tb2[i].end()); } cin >> Q; while(Q--){ cin >> k >> x; int ans = 0; for(int i1 = max(0, k - 14); i1 <= k && i1 <= 14; i1++){ int i2 = k - i1; auto f = [&](int l, int r){ r = r == m ? tb2[i2].size() : lower_bound(tb2[i2].begin(), tb2[i2].end(), r) - tb2[i2].begin(); l = l == 0 ? 0 : lower_bound(tb2[i2].begin(), tb2[i2].end(), l) - tb2[i2].begin(); return r - l; }; for(auto &&v : tb1[i1]){ if(x >= v){ ans += f(x - v, m - v); }else{ ans += f(m + x - v, m); ans += f(0, m - v); } } } cout << ans << '\n'; } }