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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

int main(){
	ll t;cin>>t;
	while(t--){
		ll n,k;cin>>n>>k;
		string s;cin>>s;
		map <ll,ll> m;
		rep(i,1,(n/2)+1){
			m[i] = i;
			m[n-i+1] = i;

		}
		if(n%2!=0) m[(n/2)+1] = (n/2)+1;

		rep(i,1,n+1){
			m[i+k] = m[i];
			m[n-(i+k)+1] = m[i];
		}

		vector <pair<ll,ll>> v;
		rep(i,1,n+1){
			v.pb({m[i],i});
		}
		sort(v.begin(),v.end());
/*		rep(i,0,v.size()){
			cout<<v[i].first<<" "<<v[i].second<<endl;
		}
		cout<<endl;*/
	//	ll f = 1;
		ll cnt[26];
		memset(cnt,0,sizeof(cnt));
		ll in = v[0].second;
		cnt[(ll)s[in-1] - 97]++;
		ll  ans=0;
		rep(i,1,v.size()){
			if(v[i].first == v[i-1].first){
				ll in = v[i].second;
				cnt[(ll)s[in-1] - 97]++;
			}
			else{
				ll sum=0;
				ll maxi=0;
				rep(i,0,26){
					sum+=cnt[i];
					maxi = max(maxi,cnt[i]);
				}
				ans += (sum - maxi) ;	memset(cnt,0,sizeof(cnt));
						ll in = v[i].second;
					cnt[(ll)s[in-1] - 97]++;
				//cout<<"ans"<<ans<<endl;
			}

		}
		ll sum=0;
		ll maxi=0;
		rep(i,0,26){
			sum+=cnt[i];
				maxi = max(maxi,cnt[i]);
		}
		ans += (sum - maxi) ;
		cout<<ans<<endl;

	}
}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<ll> adj[200005];
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	ll in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			//vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	ll t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
		}
		rep(i,1,n+1){
			if(i<n/2) adj[i].pb(n+1-i);
			//adj[n+1-i].pb(i);
			if((i+k)<=n && (i+k)!=(n+1-i)){
				adj[i].pb(i+k);
				//adj[i+k].pb(i);
			}
		}
			ll ans=0;
			memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				memset(cnt,0,sizeof(cnt));
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
			}
			cout<<ans<<endl;

	}

}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<ll> adj[200005];
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	ll in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	ll t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
		}
		rep(i,1,n+1){
			adj[i].pb(n+1-i);
			adj[n+1-i].pb(i);
			if((i+k)<=n){
				adj[i].pb(i+k);
				adj[i+k].pb(i);
			}
		}
			ll ans=0;
			memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				memset(cnt,0,sizeof(cnt));
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
			}
			cout<<ans<<endl;

	}

}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<ll> adj[200005];
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	ll in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	ll t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
		}
		rep(i,1,n+1){
			adj[i].pb(n+1-i);
			//adj[n+1-i].pb(i);
			if((i+k)<=n && (i+k)!=(n+1-i)){
				adj[i].pb(i+k);
				//adj[i+k].pb(i);
			}
		}
			ll ans=0;
			memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				memset(cnt,0,sizeof(cnt));
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
			}
			cout<<ans<<endl;

	}

}


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

    #define ll long long
    #define ld long double
    #define pb push_back

    #define sec second
    #define fir first
    #define mo 1000000007
    #define inf 1e18
    #define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

    ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
    ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

    vector<ll> adj[200005];
    bool vis[200005];
    ll cnt[27];
    string s;
    void dfs(ll u){
     	//cout<<u<<endl;
     	char c = s[u-1];
     	//cout<<c<<endl;
     	ll in = (ll)(s[u-1]) - 96;
     	cnt[in] ++ ;
     	//cout<<in<<" "<<cnt[in]<<endl;

     	vis[u]=true;
     	for(auto v :adj[u]){
     		if(vis[v]==false){
     			vis[v]=true;
     			dfs(v);
     		}
     	}
     }

    int main(){
    	ll t;cin>>t;
    	while(t--){

    		ll n,k;cin>>n>>k;

    		cin>>s;
    		rep(i,1,n+1){
    			adj[i].clear();
    		}
    		rep(i,1,n+1){
    			adj[i].pb(n+1-i);
    			adj[n+1-i].pb(i);
    			if((i+k)<=n){
    				adj[i].pb(i+k);
    				adj[i+k].pb(i);
    			}
    		}
    			ll ans=0;
    			memset(vis,false,sizeof(vis));
    			rep(i,1,n+1){
    				memset(cnt,0,sizeof(cnt));
    				if(vis[i]==false){
    					dfs(i);
    					ll sum=0;
    					ll maxi = 0;
    					rep(i,1,27){
    						sum+=cnt[i];
    						//cout<<sum<<cnt[i]<<endl;
    						maxi = max(cnt[i],maxi);
    					}

    					ans+=(sum-maxi);

    				}
    			}
    			cout<<ans<<endl;

    	}

    }


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

#define FIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<vector<ll>> adj(200005);
bool vis[200005];
ll cnt[27];
void dfs(ll u,string &s){
 	//cout<<u<<endl;
 	//char c = s[u-1];
 	//cout<<c<<endl;
 	int in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
    for(ll i=0;i<adj[u].size();i++)
    {
        if(!vis[adj[u][i]])
            dfs(adj[u][i],s);
    }
 }

int main(){
	FIO
	int t;cin>>t;
		string s;
	while(t--){

		ll n,k;cin>>n>>k;

		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
			vis[i] = false;
		}
		rep(i,1,n+1){
			 adj[i].pb(n+1-i);

		}
		rep(i,1,n+1){

			if(i+k<=n) adj[i].pb(i+k);
		}
			ll ans=0;
			//memset(vis,false,sizeof(vis));
			rep(i,1,n+1){

				if(vis[i]==false){
									rep(i,1,26){
					cnt[i] = 0;
				}
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
				//cout<<"ans"<<ans<<endl;
			}
			cout<<ans<<endl;

	}

}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<vector<ll>> adj(200005);
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	int in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			//vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	int t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
			vis[i] = false;
		}
		rep(i,1,n+1){
			 adj[i].pb(n+1-i);
			//adj[n+1-i].pb(i);
			if((i+k)<=n ){
				adj[i].pb(i+k);
			}
		}
			ll ans=0;
			//memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				rep(i,1,26){
					cnt[i] = 0;
				}
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
				//cout<<"ans"<<ans<<endl;
			}
			cout<<ans<<endl;

	}

}


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

    #define ll long long
    #define ld long double
    #define pb push_back

    #define sec second
    #define fir first
    #define mo 1000000007
    #define inf 1e18
    #define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

    ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
    ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

    vector<ll> adj[200005];
    bool vis[200005];
    ll cnt[27];
    void dfs(ll u,string &s){
     	//cout<<u<<endl;
     	char c = s[u-1];
     	//cout<<c<<endl;
     	ll in = (ll)(s[u-1]) - 96;
     	cnt[in] ++ ;
     	//cout<<in<<" "<<cnt[in]<<endl;

     	vis[u]=true;
     	for(auto v :adj[u]){
     		if(vis[v]==false){
     			vis[v]=true;
     			dfs(v,s);
     		}
     	}
     }

    int main(){
    	ll t;cin>>t;
    	while(t--){

    		ll n,k;cin>>n>>k;
    		string s;
    		cin>>s;
    		rep(i,1,n+1){
    			adj[i].clear();
    		}
    		rep(i,1,n+1){
    			adj[i].pb(n+1-i);
    			adj[n+1-i].pb(i);
    			if((i+k)<=n){
    				adj[i].pb(i+k);
    				adj[i+k].pb(i);
    			}
    		}
    			ll ans=0;
    			memset(vis,false,sizeof(vis));
    			rep(i,1,n+1){
    				memset(cnt,0,sizeof(cnt));
    				if(vis[i]==false){
    					dfs(i,s);
    					ll sum=0;
    					ll maxi = 0;
    					rep(i,1,27){
    						sum+=cnt[i];
    						//cout<<sum<<cnt[i]<<endl;
    						maxi = max(cnt[i],maxi);
    					}

    					ans+=(sum-maxi);

    				}
    			}
    			cout<<ans<<endl;

    	}

    }


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<ll> adj[200005];
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	ll in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			//vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	ll t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
		}
		rep(i,1,n+1){
			 if(i<(n/2+1)) adj[i].pb(n+1-i);
			//adj[n+1-i].pb(i);
			if((i+k)<=n && (i+k)!=(n+1-i)){
				adj[i].pb(i+k);
				adj[i+k].pb(i);
			}
		}
			ll ans=0;
			memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				memset(cnt,0,sizeof(cnt));
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
			}
			cout<<ans<<endl;

	}

}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

#define FIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<vector<ll>> adj(200005);
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	//char c = s[u-1];
 	//cout<<c<<endl;
 	int in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
    for(ll i=0;i<adj[u].size();i++)
    {
        if(!vis[adj[u][i]])
            dfs(adj[u][i],s);
    }
 }

int main(){
	FIO
	int t;cin>>t;
		string s;
			ll n,k;
	while(t--){

	cin>>n>>k;

		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
			vis[i] = false;
		}
		rep(i,1,n+1){
			 adj[i].pb(n+1-i);

		}
		rep(i,1,n+1){

			if(i+k<=n) adj[i].pb(i+k);
		}
			ll ans=0;
			//memset(vis,false,sizeof(vis));
			rep(i,1,n+1){

				if(vis[i]==false){
									rep(i,1,26){
					cnt[i] = 0;
				}
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
				//cout<<"ans"<<ans<<endl;
			}
			cout<<ans<<endl;

	}

}


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

#define ll long long
#define ld long double
#define pb push_back

#define sec second
#define fir first
#define mo 1000000007
#define inf 1e18
#define rep(i, s, n) for (ll i = s; i < n; i = i + 1)

ll mod(ll n) { return (n % (ll)mo + (ll)mo)%(ll)mo;}
ll gcd(ll a,ll b) {if (b == 0) return a;return gcd(b, a % b);}

vector<ll> adj[200005];
bool vis[200005];
ll cnt[27];
void dfs(ll u,string s){
 	//cout<<u<<endl;
 	char c = s[u-1];
 	//cout<<c<<endl;
 	ll in = (ll)(s[u-1]) - 96;
 	cnt[in] ++ ;
 	//cout<<in<<" "<<cnt[in]<<endl;

 	vis[u]=true;
 	for(auto v :adj[u]){
 		if(vis[v]==false){
 			vis[v]=true;
 			dfs(v,s);
 		}
 	}
 }

int main(){
	ll t;cin>>t;
	while(t--){

		ll n,k;cin>>n>>k;
		string s;
		cin>>s;
		rep(i,1,n+1){
			adj[i].clear();
		}
		rep(i,1,n+1){
			adj[i].pb(n+1-i);
			//adj[n+1-i].pb(i);
			if((i+k)<=n){
				adj[i].pb(i+k);
				//adj[i+k].pb(i);
			}
		}
			ll ans=0;
			memset(vis,false,sizeof(vis));
			rep(i,1,n+1){
				memset(cnt,0,sizeof(cnt));
				if(vis[i]==false){
					dfs(i,s);
					ll sum=0;
					ll maxi = 0;
					rep(i,1,27){
						sum+=cnt[i];
						//cout<<sum<<cnt[i]<<endl;
						maxi = max(cnt[i],maxi);
					}

					ans+=(sum-maxi);

				}
			}
			cout<<ans<<endl;

	}

}


#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f3f
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);

    while (t--)
    {
        scanf("%d%d", &n, &k);
        scanf("%s", s + 1);

        for(int i = 1; i <= n; i++) {
            for(int j = 0; j < 26; j++) {
               cnt[i][j] = 0;
            }
        }
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
                res = min(res, 2 * d - cnt[l][i] - cnt[r][i]);
            ans += res;
            l++, r--;
        }

        if (l == r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
                res = min(res, d - cnt[l][i]);
            ans += res;
        }
        printf("%d\n", ans);
    }
    return 0;
}


#include <iostream>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    cin >> t;

    while (t--)
    {
        cin >> n >> k;
        cin >> (s + 1);

        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i] + cnt[r][i]);
            ans += 2 * d - res;
            l++, r--;
        }

        if (l == r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i]);
            ans += d - res;
        }
        cout << ans << endl;
    }
}


#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f3f
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);

    while (t--)
    {
        scanf("%d%d", &n, &k);
        scanf("%s", s + 1);

        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
                res = min(res, 2 * d - cnt[l][i] - cnt[r][i]);
            ans += res;
            l++, r--;
        }

        if (l == r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
                res = min(res, d - cnt[l][i]);
            ans += res;
        }
        printf("%d\n", ans);
    }
    return 0;
}


#include <cstring>
#include <cstdio>
#include <iostream>
#define INF 0x3f3f3f3f
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);

    while (t--)
    {
        cin >> n >> k;
        cin >> (s + 1);
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j < 26; j++)
            {
                cnt[i][j] = 0;
            }
        }
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                ++cnt[i][s[j] - 'a'];
            }
        }
        int l = 1, r = k;
        int ans = 0;
        int d = n / k;
        while (l < r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
            {
                res = min(res, 2 * d - cnt[l][i] - cnt[r][i]);
            }
            ans += res;
            ++l, --r;
        }
        if (l == r)
        {
            int res = INF;
            for (int i = 0; i < 26; i++)
            {
                res = min(res, d - cnt[l][i]);
            }
            ans += res;
        }
        cout << ans << '\n';
    }
    return 0;
}


#include <iostream>
#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f3f
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);

    while (t--)
    {
        scanf("%d%d", &n, &k);
        scanf("%s", s + 1);

        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i] + cnt[r][i]);
            ans += 2 * d - res;
            l++, r--;
        }

        if (l == r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i]);
            ans += d - res;
        }
        printf("%d\n", ans);
    }
}


#include <iostream>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int t;
    cin >> t;

    while (t--)
    {
        cin >> n >> k;
        cin >> (s + 1);

        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i] + cnt[r][i]);
            ans += 2 * d - res;
            l++, r--;
        }

        if (l == r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i]);
            ans += d - res;
        }
        cout << ans << endl;
    }
}


#include <cstring>
#include <cstdio>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
const int MAXN = 2e5 + 5;
int cnt[MAXN][26], n, k;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);

    while (t--)
    {
        scanf("%d%d", &n, &k);
        scanf("%s", s + 1);

        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= k; i++)
        {
            for (int j = i; j <= n; j += k)
            {
                cnt[i][s[j] - 'a']++;
            }
        }

        int l = 1, r = k;
        int ans = 0, d = n / k;
        while (l < r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i] + cnt[r][i]);
            ans += 2 * d - res;
            l++, r--;
        }

        if (l == r)
        {
            int res = 0;
            for (int i = 0; i < 26; i++)
                res = max(res, cnt[l][i]);
            ans += d - res;
        }
        printf("%d\n", ans);
    }
    return 0;
}


//Fall 7, Stand 8...
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<"->"<<x<<endl;
template<typename...T>void input(T &...args){((cin >> args), ...);}
template<typename...T>void print(T &&...args){((cout<<args<<endl),...);}
#define forr(x, a, m) for(int x=a;x<m;x+=1)
bool rev(long long int x, long long int y){return x>y;}
#define stand8th ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define elif else if
#define endl '\n'
#define int long long
#define ldd long double
void print_vec(vector<int> &v){for (auto i:v) cout << i << " ";cout << endl;}
void print_arr(int a[], int n){forr(i, 0, n) cout << a[i] << " ";cout << endl;}
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) (x).begin(),(x).end()
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
void input_arr(int a[],int n){forr(i,0,n)input(a[i]);}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
int DFS(int n,int k,string &a,int z,vector<int> &s){
    s[a[z]-'a']+=1;
    a[z]=' ';
    if(a[n-z-1]!=' '){
        DFS(n,k,a,n-z-1,s);
    }
    if(z+k<n&&a[z+k]!=' ')
        DFS(n,k,a,z+k,s);
    int mixx=INT64_MIN; int summ=0;
    forr(i,0,26){
        if(mixx<s[i])
            mixx=s[i];
        summ+=s[i];
    }
    int f=summ-mixx;
    return f;
}
void solve(){
    int n,k; input(n,k);
    string s; input(s);
    int ans=0;
    forr(i,0,n){
        if(s[i]!=' '){
            vector<int>a(26,0);
            ans+=DFS(n,k,s,i,a);
            a.clear();
        }
    }
    print(ans);
}
signed main() {
    stand8th;
    int tin = 1; input(tin);
    //int joker=1;
    while (tin--){
        //cout<<"Case #"<<joker<<": ";
        solve();
        //joker++;
    }
    return 0;
}


//Fall 7, Stand 8...
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<"->"<<x<<endl;
template<typename...T>void input(T &...args){((cin >> args), ...);}
template<typename...T>void print(T &&...args){((cout<<args<<endl),...);}
#define forr(x, a, m) for(int x=a;x<m;x+=1)
bool rev(long long int x, long long int y){return x>y;}
#define stand8th ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define elif else if
#define endl '\n'
#define int long long
#define ldd long double
void print_vec(vector<int> &v){for (auto i:v) cout << i << " ";cout << endl;}
void print_arr(int a[], int n){forr(i, 0, n) cout << a[i] << " ";cout << endl;}
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) (x).begin(),(x).end()
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
void input_arr(int a[],int n){forr(i,0,n)input(a[i]);}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
vector<char> DFS(int n,int k,string a,int z,vector<int>&visited,vector<char> &s,int val){
    visited[z]=1;
    //deb(z);
    val+=1;
    s.pb(a[z]);
    if(visited[n-z-1]==0){
        DFS(n,k,a,n-z-1,visited,s,val);
    }
    if(z+k<n&&!visited[z+k])
        DFS(n,k,a,z+k,visited,s,val);
    return s;
}
void solve(){
    int n,k; input(n,k);
    string s; input(s);
    vector<int>visited(n+1,0);
    int ans=0;
    forr(i,0,n){
        if(!visited[i]){
            vector<char>a;
            int val=0;
            vector<char>f=DFS(n,k,s,i,visited,a,val);
            int size=0;
            set<char>stt;
            for(auto vbn: f){
                if(vbn-'a'>=0&&'z'-vbn<=26)
                    size+=1;
                stt.insert(vbn);
            }
            set<char>::iterator it; int happ=0;
            int mix=INT64_MIN;
            for(it=stt.begin();it!=stt.end();it++){
                happ=0;
                forr(i,0,f.size()){
                    if(*it==f[i])
                        happ+=1;
                }
                if(happ>mix) mix=happ;
            }
            stt.clear(); f.clear(); a.clear();
            ans+=size-mix;
        }
    }
    print(ans);
}
signed main() {
    stand8th;
    int tin = 1; input(tin);
    //int joker=1;
    while (tin--){
        //cout<<"Case #"<<joker<<": ";
        solve();
        //joker++;
    }
    return 0;
}


//Fall 7, Stand 8...
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<"->"<<x<<endl;
template<typename...T>void input(T &...args){((cin >> args), ...);}
template<typename...T>void print(T &&...args){((cout<<args<<endl),...);}
#define forr(x, a, m) for(int x=a;x<m;x+=1)
bool rev(long long int x, long long int y){return x>y;}
#define stand8th ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define elif else if
#define endl '\n'
#define int long long
#define ldd long double
void print_vec(vector<int> &v){for (auto i:v) cout << i << " ";cout << endl;}
void print_arr(int a[], int n){forr(i, 0, n) cout << a[i] << " ";cout << endl;}
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) (x).begin(),(x).end()
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
void input_arr(int a[],int n){forr(i,0,n)input(a[i]);}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
int DFS(int n,int k,string &a,int z,vector<int> &s){
    s[a[z]-'a']+=1;
    a[z]=' ';
    if(a[n-z-1]!=' '){
        DFS(n,k,a,n-z-1,s);
    }
    if(z+k<n&&s[z+k]!=' ')
        DFS(n,k,a,z+k,s);
    int mixx=INT64_MIN; int summ=0;
    forr(i,0,s.size()){
        if(mixx<s[i])
            mixx=s[i];
        summ+=s[i];
    }
    int f=summ-mixx;
    return f;

}
void solve(){
    int n,k; input(n,k);
    string s; input(s);
    int ans=0;
    forr(i,0,n){
        if(s[i]!=' '){
            vector<int>a(26,0);
            ans+=DFS(n,k,s,i,a);
        }
    }
    print(ans);
}
signed main() {
    stand8th;
    int tin = 1; input(tin);
    //int joker=1;
    while (tin--){
        //cout<<"Case #"<<joker<<": ";
        solve();
        //joker++;
    }
    return 0;
}


//Fall 7, Stand 8...
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<"->"<<x<<endl;
template<typename...T>void input(T &...args){((cin >> args), ...);}
template<typename...T>void print(T &&...args){((cout<<args<<endl),...);}
#define forr(x, a, m) for(int x=a;x<m;x+=1)
bool rev(long long int x, long long int y){return x>y;}
#define stand8th ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define elif else if
#define endl '\n'
#define int long long
#define ldd long double
void print_vec(vector<int> &v){for (auto i:v) cout << i << " ";cout << endl;}
void print_arr(int a[], int n){forr(i, 0, n) cout << a[i] << " ";cout << endl;}
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) (x).begin(),(x).end()
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
void input_arr(int a[],int n){forr(i,0,n)input(a[i]);}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
vector<char> DFS(int n,int k,string a,int z,vector<int>&visited,vector<char> &s,int val){
    visited[z]=1;
    //deb(z);
    val+=1;
    s.pb(a[z]);
    if(visited[n-z-1]==0){
        DFS(n,k,a,n-z-1,visited,s,val);
    }
    if(z+k<n&&!visited[z+k])
        DFS(n,k,a,z+k,visited,s,val);
    return s;
}
void solve(){
    int n,k; input(n,k);
    string s; input(s);
    vector<int>visited(n+1,0);
    int ans=0;
    forr(i,0,n){
        if(!visited[i]){
            vector<char>a;
            int val=0;
            vector<char>f=DFS(n,k,s,i,visited,a,val);
            int size=0;
            set<char>stt;
            for(auto vbn: f){
                if(vbn-'a'>=0&&'z'-vbn<=26)
                    size+=1;
                stt.insert(vbn);
            }
            set<char>::iterator it; int happ=0;
            int mix=INT64_MIN;
            for(it=stt.begin();it!=stt.end();it++){
                happ=0;
                forr(i,0,f.size()){
                    if(*it==f[i])
                        happ+=1;
                }
                if(happ>mix) mix=happ;
            }
            ans+=size-mix;
        }
    }
    print(ans);
}
signed main() {
    stand8th;
    int tin = 1; input(tin);
    //int joker=1;
    while (tin--){
        //cout<<"Case #"<<joker<<": ";
        solve();
        //joker++;
    }
    return 0;
}


//Fall 7, Stand 8...
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<"->"<<x<<endl;
template<typename...T>void input(T &...args){((cin >> args), ...);}
template<typename...T>void print(T &&...args){((cout<<args<<endl),...);}
#define forr(x, a, m) for(int x=a;x<m;x+=1)
bool rev(long long int x, long long int y){return x>y;}
#define stand8th ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define elif else if
#define endl '\n'
#define int long long
#define ldd long double
void print_vec(vector<int> &v){for (auto i:v) cout << i << " ";cout << endl;}
void print_arr(int a[], int n){forr(i, 0, n) cout << a[i] << " ";cout << endl;}
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) (x).begin(),(x).end()
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);}
void input_arr(int a[],int n){forr(i,0,n)input(a[i]);}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
vector<char> DFS(int n,int k,string a,int z,vector<int>&visited,vector<char> &s,int val){
    visited[z]=1;
    //deb(z);
    val+=1;
    s[a[z]-'a']+=1;
    if(visited[n-z-1]==0){
        DFS(n,k,a,n-z-1,visited,s,val);
    }
    if(z+k<n&&!visited[z+k])
        DFS(n,k,a,z+k,visited,s,val);
    return s;
}
void solve(){
    int n,k; input(n,k);
    string s; input(s);
    vector<int>visited(n+1,0);
    int ans=0;
    forr(i,0,n){
        if(!visited[i]){
            vector<char>a(26,0);
            int val=0;
            vector<char>f=DFS(n,k,s,i,visited,a,val);
            int mixx=INT64_MIN; int summ=0;
            forr(i,0,a.size()){
                if(mixx<a[i])
                    mixx=a[i];
                summ+=a[i];
            }
            ans+=summ-mixx;
        }
    }
    print(ans);
}
signed main() {
    stand8th;
    int tin = 1; input(tin);
    //int joker=1;
    while (tin--){
        //cout<<"Case #"<<joker<<": ";
        solve();
        //joker++;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define FAST_IO ios_base::sync_with_stdio(),cout.tie(NULL),cin.tie(NULL);
#define pb push_back
#define ss second
#define ff first
const int N = 2e5 + 5;
int arr[N];

int find(int i)
{
	if (arr[i] == i)return i;
	return arr[i] = find(arr[i]);
}
int main()
{
	FAST_IO;
	int t;
    scanf("%d",&t);
    while(t--){
        int n,k;
        scanf("%d %d",&n,&k);
        int dp[n+1][26];
		string s;
		cin >> s;
		for (int i = 0; i < n; i++)
		{
			arr[i] = i;
		}
		for (int i = 0; i < n/2; i++)
		{
			arr[find(i)] = arr[find(n - 1 - i)];
		}
		for (int i = 0; i < n - k; i++)
		{
			arr[find(i)] = arr[find(i + k)];
		}
		for (int i = 0; i < n; i++)
		{
			dp[find(i)][s[i] - 'a']++;
		}
		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			if (arr[i] == i)
			{
				int tot = 0;
				int mx = 0;
				for (int j = 0; j < 26; j++)
				{
					mx = max(mx, dp[i][j]);
					tot += dp[i][j];
				}
				ans += tot - mx;
			}
		}
		cout << ans << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define FAST_IO ios_base::sync_with_stdio(),cout.tie(NULL),cin.tie(NULL);
#define pb push_back
#define ss second
#define ff first
const int N = 2e5 + 5;
int arr[N];
int dp[N][26];
int find(int i)
{
	if (arr[i] == i)return i;
	else return arr[i] = find(arr[i]);
}
int main()
{
	FAST_IO;
	int t;
	cin >> t;
	while (t--)
	{
		memset(dp, 0, sizeof(dp));
		int n, k;
		cin >> n >> k;
		string s;
		cin >> s;
		for (int i = 0; i < n; i++)
		{
			arr[i] = i;
		}
		for (int i = 0; i < n; i++)
		{
			arr[find(i)] = arr[find(n - 1 - i)];
		}
		for (int i = 0; i < n - k; i++)
		{
			arr[find(i)] = arr[find(i + k)];
		}
		for (int i = 0; i < n; i++)
		{
			dp[find(i)][s[i] - 'a']++;
		}
		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			if (arr[i] == i)
			{
				int tot = 0;
				int mx = 0;
				for (int j = 0; j < 26; j++)
				{
					mx = max(mx, dp[i][j]);
					tot += dp[i][j];
				}
				ans += tot - mx;
			}
		}
		cout << ans << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define FAST_IO ios_base::sync_with_stdio(),cout.tie(NULL),cin.tie(NULL);
#define pb push_back
#define ss second
#define ff first
const int N = 2e5 + 5;
int arr[N];

int find(int i)
{
	if (arr[i] == i)return i;
	return arr[i] = find(arr[i]);
}
int main()
{
	FAST_IO;
	int t;
    scanf("%d",&t);
    while(t--){
        int n,k;
        scanf("%d %d",&n,&k);
        int dp[N][26];
		string s;
		cin >> s;
		for (int i = 0; i < n; i++)
		{
			arr[i] = i;
		}
		for (int i = 0; i < n/2; i++)
		{
			arr[find(i)] = arr[find(n - 1 - i)];
		}
		for (int i = 0; i < n - k; i++)
		{
			arr[find(i)] = arr[find(i + k)];
		}
		for (int i = 0; i < n; i++)
		{
			dp[find(i)][s[i] - 'a']++;
		}
		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			if (arr[i] == i)
			{
				int tot = 0;
				int mx = 0;
				for (int j = 0; j < 26; j++)
				{
					mx = max(mx, dp[i][j]);
					tot += dp[i][j];
				}
				ans += tot - mx;
			}
		}
		cout << ans << endl;
	}
	return 0;
}


n=int(input())
l=list(map(int,input().split()))
ml=[0]*(n)
ml[0]=l[0]
for i in range(1,n):
	ml[i]=max(l[i],ml[i-1])
for i in range(int(input())):
	w,h=map(int,input().split())
	print(ml[w-1])
	t=ml[w-1]
	for i in range(n):
		ml[i]=max(t+h,ml[i])


n=int(input())
l=list(map(int,input().split()))
ml=[0]*(n)
ml[0]=l[0]
for i in range(1,n):
	ml[i]=max(l[i],ml[i-1])
for i in range(int(input())):
	w,h=map(int,input().split())
	print(ml[w-1])
	t=ml[w-1]
	for i in range(w):
		ml[i]=t+h


n = int(input())
l = list(map(int,input().split()))
m = int(input())
w = []
h = []
for i in range(m):
    x,y = map(int,input().split())
    w.append(x)
    h.append(y)
cur = 0
for i in range(m):
    cur = max(cur, l[w[i]-1])
    print(cur)
    cur += h[i]


n=int(input())
l=list(map(int,input().split()))
g=l[0]
m=int(input())
S=''
for i in range(m) :
    a,b=map(int,input().split())
    t=max(l[0],l[a-1])
    S+=str(t-g+1)+'\n'
    l[0]=t+b
    l[a-1]=t+b
print(S)


n=int(input())
l=list(map(int,input().split()))
g=l[0]
m=int(input())
S=''
for i in range(m) :
    a,b=map(int,input().split())
    t=max(l[0],l[a-1])
    S+=str(t)+'\n'
    l[0]=t+b
    l[a-1]=t+b
print(S)


__author__ = "runekri3"

stairs_amount = int(input())
stair_heights = list(map(int, input().split()))
boxes_amount = int(input())
boxes = []
for _ in range(boxes_amount):
    boxes.append(list(map(int, input().split())))

for width, height in boxes:
    box_bottom = max(stair_heights[0], stair_heights[width - 1])
    print(box_bottom)
    stair_heights[0] = box_bottom + height


_ = input()
a = list(map(int, input().split(' ')))
m = input()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    cmax = a[w-1]
    print(cmax)
    for x in range(w):
        a[x] = cmax + h


_ = input()
a = list(map(int, input().split(' ')))
m = input()

res = list()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    res.append(cmax)
    # for x in range(w):
    #     a[x] = cmax + h
    a[0] = cmax + h
    a[w-1] = cmax + h

    #print(a)

print('\n'.join(map(str, res)))


_ = input()
a = list(map(int, input().split(' ')))
m = input()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    cmax = max(a[:w])
    print(cmax)
    for x in range(w):
        a[x] = cmax + h


_ = input()
a = list(map(int, input().split(' ')))
m = input()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    print(cmax)
    # for x in range(w):
    #     a[x] = cmax + h
    a[0] = cmax + h
    a[w-1] = cmax + h

    #print(a)


_ = input()
a = list(map(int, input().split(' ')))
m = input()

res = list()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    res.append(cmax)
    # for x in range(w):
    #     a[x] = cmax + h
    a[0] = cmax + h
    #a[w-1] = cmax + h

    #print(a)

print('\n'.join(map(str, res)))


_ = input()
a = list(map(int, input().split(' ')))
m = input()

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    print(cmax)
    for x in range(w):
        a[x] = cmax + h

    #print(a)


_ = input()
a = list(map(int, input().split(' ')))
m = input()
print(a)

for _ in range(int(m)):
    w, h = map(int, input().split(' '))
    #print(w, h)
    cmax = max(a[0], a[w-1])
    print(cmax)
    for x in range(w):
        a[x] = cmax + h


def check(n , a , m , dimensions):
        result = list()
        prev = 0
        for ele in dimensions:
                w = ele[0]
                h = ele[1]

                if w <= prev:
                        maxHeight = a[prev]
                else:
                        maxHeight = max(a[prev:w])
                        prev = w - 1

                result.append(maxHeight)

                a[prev] = maxHeight + h

        return result

if __name__ == "__main__":
        n = int(input().rstrip())
        a = list(map(int , input().rstrip().split()))
        m = int(input().rstrip())

        dimensions = list()
        for i in range(m):
                temp = list(map(int , input().rstrip().split()))
                w = temp[0]
                h = temp[1]
                dimensions.append((w , h))

        result = check(n , a , m , dimensions)
        for i in result:
                print (i)


def check(n , a , m , dimensions):
        result = list()

        for ele in dimensions:
                w = ele[0]
                h = ele[1]
                maxHeight = max(a[:w])
                result.append(maxHeight)

                a[:w] = [maxHeight + h] * w
        return result

if __name__ == "__main__":
        n = int(input().rstrip())
        a = list(map(int , input().rstrip().split()))
        m = int(input().rstrip())

        dimensions = list()
        for i in range(m):
                temp = list(map(int , input().rstrip().split()))
                w = temp[0]
                h = temp[1]
                dimensions.append((w , h))

        result = check(n , a , m , dimensions)
        for i in result:
                print (i)


def check(n , a , m , dimensions):
        result = list()
        prev = 0
        for ele in dimensions:
                w = ele[0]
                h = ele[1]

                if w <= prev:
                        maxHeight = str(int(maxHeight) + h)
                else:
                        maxHeight = max(a[prev:w])
                        prev = w - 1

                result.append(maxHeight)

                a[w - 1] = str(int(maxHeight) + h)
        return result

if __name__ == "__main__":
        n = int(input().rstrip())
        a = input().rstrip().split()
        m = int(input().rstrip())

        dimensions = list()
        for i in range(m):
                temp = list(map(int , input().rstrip().split()))
                w = temp[0]
                h = temp[1]
                dimensions.append((w , h))

        result = check(n , a , m , dimensions)
        for i in result:
                print (i)


n, t, d, p = input(), [0] + list(map(int, input().split())), 0, []
for i in range(int(input())):
    w, h = map(int, input().split())
    p.append(max(d, t[w]))
    d = p[i] + h
print(' '.join(map(str, p)))


n, t, d, p = input(), [0] + list(map(int, input().split())), 0, []

for i in range(int(input())):

    w, h = map(int, input().split())

    p.append(max(d, t[w]))

    d = p[i] + h

print(' '.join(map(str, p)))

# Made By Mostafa_Khaled


stair_number = int(input())
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = map(int,input().split())
    k =max( x , stair_heights[w-1] )
    print(k)
    x = k + h


stair_number = int(input())
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = input().split()
    w ,h = int(w) , int(h)
    if x >= stair_heights[w-1] :
        k = x
    else :
        k = stair_heights[w-1]
    print(k)
    x = k + h


stair_number = input()
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = input().split()
    w ,h = int(w) , int(h)
    m = stair_heights[w-1]
    if x >= m:
        k = x
    else :
        k = m
    print(k)
    x = k + h


stair_number = int(input())
stair_heights = list(map(int,input().split()))
box_number = int(input())

for _ in range(box_number)  :
    w , h = map(int,input().split())
    mx = max(stair_heights[:w])
    print(mx)
    for inx in range(w) :
        stair_heights[inx] = mx +h


stair_number = input()
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = input().split()
    w ,h , m= int(w) , int(h) ,stair_heights[w-1]
    if x >= m:
        k = x
    else :
        k = m
    print(k)
    x = k + h


stair_number = int(input())
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = map(int,input().split())
    if x >= stair_heights[w-1] :
        k = x
    else :
        k = stair_heights[w-1]
    print(k)
    x = k + h


stair_number = int(input())
stair_heights = list(map(int,input().split()))
box_number = int(input())

x = stair_heights[0]

for _ in range(box_number)  :
    w , h = map(int,input().split())
    print( max( x , stair_heights[w-1] ) )
    x = max( x , stair_heights[w-1] ) + h


n = int(input())
arr = [int(x) for x in input().strip().split()]
m = int(input())
curr = 0
q = []
for i in range(0,m):
	k = [int(x) for x in input().strip().split()]
	q.append(k)
	# if arr[w-1]+h>w:
	# 	k = arr[w-1]
	# 	for i in range(w-1,min(arr[w-1]+h,n)):
	# 		arr[i] = max(k+h,arr[i])
	# #print(arr,"2")
	# for i in range(0,w-1):
	# 	arr[i]=arr[w-1]
	# #print(arr,"3")
for i in q:
	w,h=i
	print(max(curr,arr[w-1]))
	#print(arr,"1")
	curr = max(curr,max(curr,arr[w-1])+h)
	arr[w-1] = curr


n=int(input())
A=[0]+[int(x) for x in input().split()]
m=int(input())
curHeight=0
# print(A)
Answer=[]
for i in range(m):
  a,b=map(int, input().split())
  curHeight=max(curHeight,A[a])
  Answer.append(str(curHeight))
  curHeight+=b
print("\n".join(Answer))


n=int(input())
A=[0]+[int(x) for x in input().split()]
m=int(input())
curHeight=0
# print(A)
for i in range(m):
  a,b=map(int, input().split())
  curHeight=max(curHeight,A[a])
  print(curHeight)
  curHeight+=b


n=int(input())
arr=[int(i) for i in input().split()]
arr.insert(0,0)
m=int(input())
last=1
for _ in range(m):
    a,b=map(int,input().split())
    if a>=last:
        print(arr[a])
        arr[a]+=b
        last=a
    else:
        print(arr[last])
        arr[last]+=b


n=int(input())
arr=[int(i) for i in input().split()]
arr.insert(0,0)
m=int(input())
last=1
for _ in range(m):
    a,b=map(int,input().split())
    if a>=last:
        print(arr[a])
        arr[a]+=b
        last=a
    else:
        print(arr[last])
        arr[a]+=b


n=int(input())
arr=[int(i) for i in input().split()]
arr.insert(0,0)
m=int(input())
last=1
for _ in range(m):
    a,b=map(int,input().split())
    if a>=last:
        print(arr[a])
        arr[a]+=b
        last=a
    else:
        print(arr[last])


n=int(input())
arr=[int(i) for i in input().split()]
arr.insert(0,0)
m=int(input())
last=1
for _ in range(m):
    a,b=map(int,input().split())
    if a>=last and arr[a]>arr[last]:
        print(arr[a])
        arr[a]+=b
        last=a
    else:
        print(arr[last])
        arr[last]+=b


n = int(input())
lis= list(map(int,input().split()))
a = int(input())
que = []
hi =  []
co = 0
for i in range(a):
	que.append(list(map(int,input().split())))
i=0
while i < a:
	(w,h) = que[i]
	if lis[w-1]>=w:
		if lis[w-1]>=co:
			hi.append(lis[w-1])
			co = max(co, lis[w-1] + h)
		else:
			hi.append(co)
			co+= h
	else:
		if w>=co:
			hi.append(lis[w-1])
			co = max(co, lis[w-1] + h)
		else:
			hi.append(co)
			co+= h
	i+=1
for i in hi:
	print(i)


def main():
    n, res = int(input()), []
    l = list(map(int, input().split()))
    for _ in range(int(input())):
        w, h = map(int, input().split())
        m = max(l[0], l[w - 1])
        res.append(m)
        l[0] = m + h
    print('\n'.join(map(str, res)))

if __name__ == '__main__':
    main()


from sys import stdin
inp = lambda: list(map(int, stdin.readline().split()))
inp()
aa = inp()
for i in range(inp()[0]):
    a,b=inp()
    k=max(aa[0],aa[a-1])
    aa[0]=k+b
    print(k)


num_stairs = int(input())
stair_list = [int(x) for x in input().split()]
relative_height = 0
for _ in range(int(input())):
	width, height = [int(x) for x in input().split()]
	cur_height = stair_list[width - 1]
	new_height = max(cur_height, relative_height)
	print(max(cur_height, relative_height))
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])


num_stairs = int(input())
stair_list = [int(x) for x in input().split()]

for _ in range(int(input())):
	width, height = [int(x) for x in input().split()]
	cur_height = stair_list[width - 1]
	print(cur_height)
	new_height = cur_height + height
	# print("New Height: ", new_height)
	for x in range(width):
		stair_list[x] = new_height
		# print(x, stair_list[x])
	for y in range(width, len(stair_list)):
		if stair_list[y] >= new_height:
			# print(stair_list[y])

			break
		else:
			stair_list[y] = new_height
			# print(stair_list[y])


num_stairs = int(input())
stair_list = list(map(int, input().split()))
relative_height = 0
solutions = []
for _ in range(int(input())):
	width, height = map(int, input().split())
	new_height = max(stair_list[width - 1], relative_height)
	solutions.append(new_height)
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])
# Joining is much faster than individually printing
print(' '.join(map(str, solutions)))


num_stairs = int(input())
stair_list = [int(x) for x in input().split()]
relative_height = 0
for _ in range(int(input())):
	width, height = [int(x) for x in input().split()]
	new_height = max(stair_list[width - 1], relative_height)
	print(new_height)
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])


num_stairs = int(input())
stair_list = [int(x) for x in input().split()]

for _ in range(int(input())):
	width, height = [int(x) for x in input().split()]
	cur_height = stair_list[width - 1]
	print(cur_height)
	new_height = cur_height + height
	for x in range(width):
		stair_list[x] = new_height
	for y in range(width, len(stair_list)):
		if stair_list[x] >= new_height:
			break
		else:
			stair_list[x] = new_height


n, t, d, p = input(), [0] + list(map(int, input().split())), 0, []
for i in range(int(input())):
    w, h = map(int, input().split())
    p.append(max(d, t[w]))
    d = p[i] + h
print(' '.join(map(str, p)))


num_stairs = int(input())
stair_list = list(map(int, input().split()))
relative_height = 0
for _ in range(int(input())):
	width, height = map(int, input().split())
	new_height = max(stair_list[width - 1], relative_height)
	print(new_height)
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])


num_stairs = int(input())
stair_list = list(map(int, input().split()))
relative_height = 0
solutions = []
for _ in range(int(input())):
	width, height = map(int, input().split())
	new_height = max(stair_list[width - 1], relative_height)
	solutions.append(new_height)
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])
print(' '.join(map(str, solutions)))


num_stairs = int(input())
stair_list = [int(x) for x in input().split()]
relative_height = 0
for _ in range(int(input())):
	width, height = [int(x) for x in input().split()]
	cur_height = stair_list[width - 1]
	new_height = max(cur_height, relative_height)
	print(new_height)
	relative_height = new_height + height
	# print("New Height: ", new_height)
	# for x in range(width):
	# 	stair_list[x] = new_height
	# 	# print(x, stair_list[x])
	# for y in range(width, len(stair_list)):
	# 	if stair_list[y] >= new_height:
	# 		# print(stair_list[y])

	# 		break
	# 	else:
	# 		stair_list[y] = new_height
			# print(stair_list[y])


n=int(input())
l=list(map(int,input().split()))
m=int(input())
s=[]
for i in range(m):
	s+=[list(map(int,input().split()))]
h=[]
a=0
for i in range(m):
	b=l[s[i][0]-1]
	t=max(b,a+1)
	h+=[t]
	a=t+s[i][1]-1

for i in h:
	print(i)


n=gets.to_i
a=gets.split.map(&:to_i)
gets.to_i.times do
    w,h=gets.split.map(&:to_i)
    t=[a[0], a[w-1]].max
    puts t
    a[0]=t+h
end


n = gets.to_i #kol stypenei
a = gets.split(' ').collect!{|i| i.to_i} #visota stypenei
m = gets.to_i #kol korobok

w = []
h = []
m.times do
	t=gets.split(' ')
	w << t[0].to_i
	h << t[1].to_i
end

x = []

# m.times do |i|
# 	wid = w[i]-1
# 	hei = h[i]
# 	x << a[wid]
# 	newhei = a[wid]+hei
# 	n.times do |j|
# 		if newhei > a[j]
# 			a[j] = newhei
# 		else
# 			break
# 		end
# 	end
# end
newhei = 0
m.times do |i|
	wid = w[i]-1
	if a[wid] > newhei
		x << a[wid]
		newhei = a[wid]+h[i]
	else
		x << newhei
		newhei += h[i]
	end
end

puts x


n = gets.to_i #kol stypenei
a = gets.split(' ').collect!{|i| i.to_i} #visota stypenei
m = gets.to_i #kol korobok

w = []
h = []
m.times do
	t=gets.split(' ')
	w << t[0].to_i
	h << t[1].to_i
end

x = []

m.times do |i|
	wid = w[i]-1
	hei = h[i]
	x << a[wid]
	newhei = a[wid]+hei
	(0..(wid)).each do |j|
		a[j] = newhei
	end
end

puts x


n = gets.to_i #kol stypenei
a = gets.split(' ').collect!{|i| i.to_i} #visota stypenei
m = gets.to_i #kol korobok

w = []
h = []
m.times do
	t=gets.split(' ')
	w << t[0].to_i
	h << t[1].to_i
end

x = []

m.times do |i|
	wid = w[i]-1
	hei = h[i]
	x << a[wid]
	newhei = a[wid]+hei
	n.times do |j|
		if newhei > a[j]
			a[j] = newhei
		else
			break
		end
	end
end

puts x


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    p = max(n[0], n[w-1])
    print p
    n[0] = p + h


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    p = max(n[:w])
    print p
    for j in xrange(w):
        n[j] = p + h


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    print max(set(n)[:w])
    p = max(n[:w])
    for j in xrange(w):
        n[j] = p + h


R=input
S=lambda: map(int, raw_input().split())
m=R()
n=S()
t=R()
for i in xrange(t):
  w,h= S()
  p=max(n[0],n[w-1])
  print p
  n[0]=p+h


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    p = max(n[:w])
    print p
    n[0] = p + h


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    print max(n[:w])
    p = max(n[:w])
    for j in xrange(w):
        n[j] = p + h


R=input
S=lambda:map(int,raw_input().split())
m=R()
n=S()
t=R()
for i in xrange(t):
  w,h= S()
  p=max(n[0],n[w-1])
  print p
  n[0]=p+h


m = input()
n = map(int, raw_input().split())
t = input()
for i in xrange(t):
    w, h = map(int, raw_input().split())
    print max(n[:w])
    for j in xrange(w):
        n[j] = max(n[:w]) + h


R=input
S = lambda: map(int, raw_input().split())
m=R()
n=S()
t=R()
for i in xrange(t):
  w,h= S()
  p=max(n[0],n[w-1])
  print p
  n[0]=p+h


while (True):
    try:
        n = input()
        a = raw_input()
        a = a.split()

        m = input()

        H = 0

        for i in range (0,m):
            b = raw_input()
            b = b.split()

            w = int(b[0])-1
            h = int(b[1])

            H = max(H,int(a[w]))

            print H

            H += h

    except EOFError:
        break


n = int(raw_input())
stairs = [int(x) for x in raw_input().split()]
m = int(raw_input())
boxes = [[int(x) for x in  raw_input().split()] for _ in range(m)]

h_0 = stairs[0]
for w,h in boxes:
    h_0 = max(h_0,stairs[w-1])
    print h_0
    h_0 += h


n= input()
s= raw_input().split(' ')
sw= [n]
sh= [2**32]
top= 0

def pop():
    global top
    sw.pop()
    sh.pop()
    top= top-1

def push(w, h):
    global top
    sw.append(w)
    sh.append(h)
    top= top+1

def init():
    x= n
    last= sh[0]
    while x>0:
        x= x-1
        h= int(s[x])
        while h>=sh[top]:
            pop()
        push(x, h)

def work():
    m= input()
    while m>0:
        m= m -1
        inp= raw_input().split(' ')
        w= int(inp[0])
        h= int(inp[1])
        h0= 0
        while w>sw[top]:
            if sh[top]>h0:
                h0= sh[top]
            pop()
        push(0, h+h0)
        print h0

init()
work()


import sys

inp = sys.stdin.read().strip().splitlines()
steps = [int(i) for i in inp[1].split(' ')]
boxes = [tuple([int(k) for k in j.split(' ')]) for j in inp[3:]]

cur = steps[0]
res = [0]*len(boxes)
for i, v in enumerate(boxes):
    w, h = v
    if w > len(steps):
        sth = steps[-1]
    else:
        sth = steps[w-1]
    cur = max(sth, cur)
    res[i] = cur
    cur += h

sys.stdout.write('\n'.join([str(i) for i in res]))


R=lambda:map(int,raw_input().split())
n,k=input(),0
a=[0]+R()
for _ in range(input()):
  w,h=R()
  k=max(w,k)
  print a[k]
  h+=a[k]
  while k<n and a[k+1]<h:k+=1
  a[k]=h


import sys
import collections

memo = {}

n = int(raw_input())
stair = map(int, sys.stdin.readline().split())

m = int(raw_input())
block = []
for i in xrange(m):
    block.append(map(int, sys.stdin.readline().split()))

cur_h = stair[0]
result = []
for b in block:
    temp_h = max(cur_h, stair[b[0] - 1])
    result.append(temp_h)
    cur_h = temp_h + b[1]

for r in result:
    print r


#!/usr/bin/python
from __future__ import division
from sys import stdin, stdout, maxint

N = int (stdin.readline ())
arr = map (int, stdin.readline ().split ())

M = int (stdin.readline ())
last = 0

for m in xrange (M):
	w, h = map (int, stdin.readline ().split ())

	res = max (last, arr[w - 1])
	print res

	last = res + h


from __future__ import print_function, division
input = raw_input

m = int(input())
a = map(int, input().split())

cur_h = 0
n = int(input())
for i in xrange(n):
    w, h = map(int, input().split())
    ch = a[w-1]
    if ch > cur_h:
        print(ch)
        cur_h = ch + h
    else:
        print(cur_h)
        cur_h += h


n = input()
stairs = [int(r) for r in raw_input().split()]
m = input()
curr = 0
for _ in xrange(m):
    box = [int(r) for r in raw_input.split()]
    bottom = max(curr,stairs[box[0]-1])
    print bottom
    curr = bottom + box[1]


n = input()
stairs = [int(r) for r in raw_input().split()]
m = input()
boxes = [(d[0],d[1]) for d in raw_input().split() for _ in xrange(m)]

curr = 0
for box in boxes:
    bottom = max(curr,stairs[box[0]-1])
    print bottom
    curr = curr + bottom


n = input()
stairs = [int(r) for r in raw_input().split()]
m = input()
curr = 0
for _ in xrange(m):
    box = [int(r) for r in raw_input().split()]
    bottom = max(curr,stairs[box[0]-1])
    print bottom
    curr = bottom + box[1]


n = input()
stairs = [int(r) for r in raw_input().split()]
m = input()
boxes = []
for _ in xrange(m):
    d = [int (r) for r in raw_input.split()]
    boxes.append(d)

curr = 0
for box in boxes:
    bottom = max(curr,stairs[box[0]-1])
    print bottom
    curr = curr + box[1]


def solve(n, m, a, w, h):
  ans = [0] * m
  mx = 0
  for i in xrange(m):
    mx = max(mx, a[w[i]-1])
    ans[i] = mx
    mx += h[i]
  return ans
n = int(raw_input())
a = map(int, raw_input().split())
m = int(raw_input())
w, h = [0] * m, [0] * m
for i in xrange(m):
    w[i], h[i] = map(int, raw_input().split())
print '\n'.join(map(str, solve(n, m, a, w, h)))


class Node:
    def __init__(self, v=0):
        self.lch = self.rch = None
        self.v = v
        self.mx = 0
    def insert(self, sl, sr, vl, vr, v):
        # print 'call insert:', (sl, sr), (vl, vr)
        if sr - sl == 1:
            self.v = v
            return
        if sr - sl == vr - vl:
            self.v = v
            self.lch = self.rch = None
            return
        if self.lch is None:
            self.lch = Node(self.v)
            self.rch = Node(self.v)
        sm = (sl + sr) // 2
        if vr <= sm:
            self.lch.insert(sl, sm, vl, vr, v)
        elif vl >= sm:
            self.rch.insert(sm, sr, vl, vr, v)
        else:
            self.lch.insert(sl, sm, vl, sm, v)
            self.rch.insert(sm, sr, sm, vr, v)

    def query(self, sl, sr, vl, vr):
        if self.lch is None:
            return self.v
        sm = (sl + sr) // 2
        if vr <= sm:
            return self.lch.query(sl, sm, vl, vr)
        elif vl >= sm:
            return self.rch.query(sm, sr, vl, vr)
        else:
            mxl = self.lch.query(sl, sm, vl, sm)
            mxr = self.rch.query(sm, sr, sm, vr)
            return max(mxl, mxr)

    def img(self, sl, sr):
        a = [0] * (sr - sl)
        for i in xrange(sl, sr):
            a[i] = self.query(sl, sr, i, i+1)
        for x in a:
            print '] ' * x
        print '-'*80

def solve(n, m, a, w, h):
    root = Node()
    root.insert(0, n, 0, n, 0)
    for i in xrange(n):
        root.insert(0, n, i, i+1, a[i])
        # print 'insert', i, i+1, a[i]
        # root.img(0, n)

    ans = [0] * m
    for i in xrange(m):
        mx = root.query(0, n, 0, w[i])
        ans[i] = mx
        root.insert(0, n, 0, w[i], mx + h[i])
        # print 'insert', 0, w[i], mx + h[i]
        # root.img(0, n)
    return ans

n = int(raw_input())
a = map(int, raw_input().split())
m = int(raw_input())
w, h = [0] * m, [0] * m
for i in xrange(m):
    w[i], h[i] = map(int, raw_input().split())
print '\n'.join(map(str, solve(n, m, a, w, h)))


#include<iostream>
#include<cassert>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define For(i, n) for(i = 0; i < n; i++)
#pragma GCC diagnostic ignored "-Wsign-compare"
typedef long long LL;
using namespace std;

class Node{
public:
    Node*lch, *rch;
    LL mx;

    Node(LL v=0):mx(v),lch(NULL), rch(NULL){}

    void insert(int sl, int sr, int vl, int vr, LL v){
        if(sr - sl == vr - vl){
            this->mx = v;
            if(lch){
                lch->del(); rch->del();
                delete lch;
                delete rch;
                lch = rch = NULL;
            }
            return;
        }
        if(lch == NULL){
            lch = new Node(mx);
            rch = new Node(mx);
        }
        int sm = (sl + sr) / 2;
        if(vr <= sm){
            lch->insert(sl, sm ,vl, vr, v);
        }else if(vl >= sm){
            rch->insert(sm, sr, vl, vr, v);
        }else{
            lch->insert(sl, sm, vl, sm, v);
            rch->insert(sm, sr, sm, vr, v);
        }
        this->mx = max(lch->mx, rch->mx);
    }

    void del(){
        if(lch){
            lch->del(); rch->del();
            delete lch;
            delete rch;
            lch = rch = NULL;
        }
    }

    LL query(int sl, int sr, int vl, int vr){
        if(sr - sl == vr - vl){
            return mx;
        }
        if(not lch){
            return mx;
        }
        int sm = (sl + sr) / 2;
        if(vr <= sm){
            return lch->query(sl, sm, vl, vr);
        }else if(vl >= sm){
            return rch->query(sm, sr, vl, vr);
        }else{
            return max(lch->query(sl, sm, vl, sm), rch->query(sm, sr, sm, vr));
        }
    }
};

const int N = 100002;

int a[N], h[N], w[N];
LL ans[N];

int main(){
#ifndef DEBUG
    ios::sync_with_stdio(false);
#endif
#ifdef DEBUG
    freopen("in3", "r", stdin);
#endif
    int n, m, i;
    cin >> n;
    For(i, n) cin >> a[i];
    cin >> m;
    For(i, m){
        cin >> w[i] >> h[i];
    }
    Node* root = new Node();
    root->insert(0, n, 0, n, 0);
    For(i, n){
        root->insert(0, n, i, i + 1, a[i]);
    }
    For(i, m){
        LL mx = root->query(0, n, 0, w[i]);
        ans[i] = mx;
        root->insert(0, n, 0, w[i], mx + h[i]);
    }
    For(i, m){
        cout << ans[i] << endl;
        assert(ans[i] > 0);
    }
    return 0;
}


R=input
S=lambda:map(int,raw_input().split())
m=R()
n=S()
t=R()
for i in xrange(t):
  w,h= S()
  p=max(n[0],n[w-1])
  print p
  n[0]=p+h


import sys

f = sys.stdin#open('3.txt')

n = int(f.readline())
a = f.readline().split()
a = [int(x) for x in a]
m = int(f.readline())
c=[]
for i in range(m):
	w,h = f.readline().split()
	c.append( [int(w),int(h)] )

mx = [0]*320
max1=a[0]

for i in range(len(a)/320+1):
	mx[i]=max(a[i*320:(i+1)*320])

def get_max(A,B):
	i=A
	s = a[A]
	while i<B:
		if i%320==0 and i+320<B:
			s=max(mx[i/320],s)
			i+=320
		else:
			i+=1
			s=max(s,a[i])
	return s

for w,h in c:
	v = get_max(0,w-1)
	print max(max1,v)
	max1=max(max1,v)+h


import sys

f = sys.stdin#open('3.txt')

n = int(f.readline())
a = f.readline().split()
a = [int(x) for x in a]
m = int(f.readline())
c=[]
for i in range(m):
	w,h = f.readline().split()
	c.append( [int(w),int(h)] )

mx = [0]*320
max1=a[0]

for i in range(len(a)/320+1):
	mx[i]=max(a[i*320:(i+1)*320])

def get_max(B):
	s=0
	x=B/320
	if x>0:
		s=max(mx[:x])
	return max(s, max(a[x*320+1:B+1] or [0]))

for w,h in c:
	v = get_max(w-1)
	print max(max1,v)
	max1=max(max1,v)+h


n = input()
a = map(int, raw_input().split())
m = input()
i = 0
for _ in xrange(m):
  w, h = map(int, raw_input().split())
  if w - 1 > i and a[w - 1] > a[i]:
    i = w - 1
  print a[i]
  a[i] += h


import sys
def scan(x):
    if x == 0:
        return sys.stdin.readline()
    return int(sys.stdin.readline())
#-----------------------------------
#s = scan(0).split()

def maxi(x,p):
    i = m = 0
    while i < x:
        if int(p[i]) > m:
            m = int(p[i])
        i += 1
    return m

def zap(p,a,b,q):
    i = 0
    while i < a:
        p[i] = b + q
        i += 1
    return

n = scan(1)
W = scan(0).split()
m = scan(1)

i = 0
t = []
while i < m:
    s = scan(0).split()
    a,b = int(s[0]),int(s[1])
    k = maxi(a,W)
    t.append(k)
    zap(W,a,b,k)
    #print b
    i += 1

for e in t:
    print e


import sys
def scan():
      return sys.stdin.readline()
#-----------------------------------

n = int(scan())
W = scan().split()
m = int(scan())

i = 0
t = []

while i < m:
    s = scan().split()
    a,b = int(s[0]),int(s[1])

    if W[0] < W[a - 1]:
        t.append(W[a - 1])
        W[0] = int(W[a - 1]) + b
    else:
        t.append(W[0])
        W[0] = int(W[a - 1]) + b
    i += 1

for e in t:
    print e


import sys
def scan(x):
    if x == 0:
        return sys.stdin.readline()
    return int(sys.stdin.readline())
#-----------------------------------
#s = scan(0).split()

def maxi(x,p):
    i = m = 0
    while i < x:
        if int(p[i]) > m:
            m = int(p[i])
        i += 1
    return m

def zap(p,a,b,q):
    i = 0
    while i < a:
        p[i] = b + q
        i += 1
    return

n = scan(1)
W = scan(0).split()
m = scan(1)

i = 0
t = []
while i < m:
    s = scan(0).split()
    a,b = int(s[0]),int(s[1])
    t.append(maxi(a,W))
    zap(W,a,b,maxi(a,W))
    #print b
    i += 1

for e in t:
    print e


import sys
def scan():
      return sys.stdin.readline()
#-----------------------------------

n = int(scan())
W = scan().split()
m = int(scan())

i = 0
t = []

while i < m:
    s = scan().split()
    a,b = int(s[0]),int(s[1])

    if int(W[0]) < int(W[a - 1]):
        t.append(W[a - 1])
        W[0] = int(W[a - 1]) + b
    else:
        t.append(W[0])
        W[0] = int(W[0]) + b
    i += 1

for e in t:
    print e


n = input()
array = map(int, raw_input().split(' '))
m = input()
for x in xrange(0,m):
	a,b = map(int, raw_input().split(' '))
	print array[a-1]
	n = array[a-1]+b
	for y in xrange(0,a):
		array[y] = n


n = input()
array = map(int, raw_input().split(' '))
m = input()
aux = 0
for x in xrange(0,m):
	a,b = map(int, raw_input().split(' '))
	cur = max(array[a-1],aux)
	print cur
	aux = cur + b


n = input()
array = map(int, raw_input().split(' '))
m = input()
aux = 0
for x in xrange(0,m):
	a,b = map(int, raw_input().split(' '))
	cur = max(a,aux)
	print cur
	aux = cur + b


import sys
n=int(sys.stdin.readline())

L=list(map(int,sys.stdin.readline().split()))
m=int(sys.stdin.readline())
M=[0]*n
M[0]=L[0]
for i in range(1,n):
    M[i]=max(L[i],M[i-1])
limit=0
maxx=-1
for i in range(m):
    w,h=map(int,sys.stdin.readline().split())
    w-=1
    sys.stdout.write(str(max(maxx,M[w]))+"\n")
    maxx=max(maxx,M[w])+h


n = int(raw_input())
A = map(int, raw_input().split())
m = int(raw_input())

currMax = 0
for i in range(m):
    w, h = map(int, raw_input().split())
    if A[w-1] > currMax:
        bottom = A[w-1]
        currMax = bottom + h
    else:
        bottom = currMax
        currMax = currMax + h
    print bottom


if __name__ == '__main__':
    n = input()
    a = map(int, raw_input().split())
    m = input()
    for _ in xrange(m):
        (w, h) = map(int, raw_input().split())
        prev_h = max(a[0], a[w-1])
        print prev_h
        a[0] = prev_h + h


if __name__ == '__main__':
    n = input()
    a = map(int, raw_input().split())
    m = input()
    for _ in xrange(m):
        (w, h) = map(int, raw_input().split())
        print a[w-1]
        for i in xrange(w):
            a[i] = a[w-1] + h


if __name__ == '__main__':
    n = input()
    a = map(int, raw_input().split())
    m = input()
    for _ in xrange(m):
        (w, h) = map(int, raw_input().split())
        prev_h = max(a[0], a[w-1])
        print prev_h
        a = [prev_h+h] * w + a[w:]


n=input()
r=lambda:map(int, raw_input().split())
a=r()
m=input()
H=0

for i in range(m):
    w,h=r()
    if a[w-1] <= H:
        print H
        H+=h
    else:
        print a[w-1]
        H=h+a[w-1]


n = int(raw_input())
A = map(int, raw_input().split(' '))

m = int(raw_input())
B = [map(int, raw_input().split(' ')) for i in range(m)]

for w, h in B:
    #print A[:w]
    top = max(A[:w])
    print top
    for i in range(w):
        A[i] = top+h


n = input()
A = map(int, raw_input().split())

m = input()

for i in xrange(m):
    w, h = map(int, raw_input().split())
    r = max(A[0], A[w-1])
    print r
    A[0] = r+h


input()
a = [(x, 1) for x in map(int, raw_input().split())][ : : -1]
for _ in range(input()):
	w, h = map(int, raw_input().split())
	W = H = 0
	while W < w:
		t = a.pop()
		H = max(H, t[0])
		W += t[1]
	print H
	a.append((H + h, W))


input()
a = map(int, raw_input().split())
for _ in range(input()):
	w, h = map(int, raw_input().split())
	p = max(a[0], a[w - 1])
	print p
	a[0] = p + h


n=input()
a=map(int,raw_input().split())
#x=a[0]
for _ in range(input()):
    w,h=map(int,raw_input().split())
    z=max(a[w-1],a[0])
    print z
    a[w-1]=z+h
    a[0]=z+h


import java.io.*;
import java.math.*;
import java.util.*;

public class e {
    static int n, c;
    static int[] a, b;

    static int cmp(long x) {
        BigInteger s = BigInteger.ZERO;
        for (int i = 0; i < n; i++) {
            BigInteger p = BigInteger.valueOf(a[i]).multiply(BigInteger.valueOf(x)).
                divide(BigInteger.valueOf(b[i]));
            // System.out.println("i = " + i + " s = " + p.toString());

            s = s.add(p);

//            if (s.compareTo(BigInteger.valueOf(c-n)) > 0)
 //             return 1;
        }

//        System.out.println("x = " + x + " s = " + s.toString());

        return s.compareTo(BigInteger.valueOf(c-n));
    }

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);

        n = s.nextInt();
        c = s.nextInt();

        if (c < n) {
            System.out.println("0");
            return;
        }

        a = new int[n];
        b = new int[n];
        boolean f = true;
        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
            b[i] = s.nextInt();

            if (a[i] != 0)
                f = false;
        }

        if (f) {
            if (c == n)
                System.out.println("-1");
            else
                System.out.println("0");
            return;
        }

        long l = 1, r = 1000000000000000000l;
        // long l = 1, r = 100;
        while (l < r) {
            long m = (l+r)/2;
            if (cmp(m) < 0)
                l = m+1;
            else if (cmp(m) > 0)
                r = m-1;
            else
                r = m;
        }

        if (cmp(l) != 0) {
            System.out.println("0");
            return;
        }

        long ll = l;

 //       System.out.println("ll = " + ll);

        l = 1; r = 1000000000000000000l;
        // l = 1; r = 100;
        while (l < r) {
            long m = (l+r+1)/2;

            if (cmp(m) < 0)
                l = m+1;
            else if (cmp(m) > 0)
                r = m-1;
            else
                l = m;
        }

        long rr = r;

//        System.out.println("rr = " + rr);

        System.out.println(rr-ll+1);
    }
}


import java.io.*;
import java.math.*;
import java.util.*;

public class e {
    static int n, c;
    static int[] a, b;

    static int cmp(long x) {
        BigInteger s = BigInteger.ZERO;
        for (int i = 0; i < n; i++) {
            BigInteger p = BigInteger.valueOf(a[i]).multiply(BigInteger.valueOf(x)).
                divide(BigInteger.valueOf(b[i]));

            s = s.add(p);

//            if (s.compareTo(BigInteger.valueOf(c-n)) > 0)
 //             return 1;
        }

//        System.out.println("x = " + x + " s = " + s.toString());

        return s.compareTo(BigInteger.valueOf(c-n));
    }

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);

        n = s.nextInt();
        c = s.nextInt();

        a = new int[n];
        b = new int[n];
        boolean f = true;
        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
            b[i] = s.nextInt();

            if (a[i] != 0)
                f = false;
        }

        if (f) {
            if (c == n)
                System.out.println("-1");
            else
                System.out.println("0");
            return;
        }

        long l = 1, r = 1000000000000000000l;
        // long l = 1, r = 100;
        while (l < r) {
            long m = (l+r)/2;
            if (cmp(m) < 0)
                l = m+1;
            else if (cmp(m) > 0)
                r = m-1;
            else
                r = m;
        }

        if (cmp(l) != 0) {
            System.out.println("-1");
            return;
        }

        long ll = l;

        // System.out.println("ll = " + ll);

        l = 1; r = 1000000000000000000l;
        // l = 1; r = 100;
        while (l < r) {
            long m = (l+r+1)/2;

            if (cmp(m) < 0)
                l = m+1;
            else if (cmp(m) > 0)
                r = m-1;
            else
                l = m;
        }

        long rr = r;

        // System.out.println("rr = " + rr);

        System.out.println(rr-ll+1);
    }
}


import java.util.Scanner;

public class CF_177E {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt(), c = in.nextInt();
		int[] a = new int[n];
		int[] b = new int[n];

		double sum = 0;
		boolean nz = false;
		for(int i = 0; i < n; i++) {
			a[i] = in.nextInt();
			b[i] = in.nextInt();
			sum += a[i] / (double) b[i] + 1;
			if(a[i] > 0) {
				nz = true;
			}
		}

		if(!nz) {
			System.out.println("-1");
			return;
		}

		int x = (int) (c / sum);
		int count = 0;
		while(true) {
			int cd = 0;
			for(int i = 0; i < n; i++) {
				cd += (x * a[i]) / b[i] + 1;
			}
			if(cd == c) {
				count++;
			}
			if(cd > c) break;

			x++;
		}

		System.out.println(count);

	}

}


import java.util.Scanner;

public class CF_177E {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt(), c = in.nextInt();
		int[] a = new int[n];
		int[] b = new int[n];

		double sum = 0;
		for(int i = 0; i < n; i++) {
			a[i] = in.nextInt();
			b[i] = in.nextInt();
			sum += a[i] / (double) b[i] + 1;
		}

		if(sum == n) {
			System.out.println("-1");
			return;
		}

		int x = (int) (c / sum);
		int count = 0;
		while(true) {
			int cd = 0;
			for(int i = 0; i < n; i++) {
				cd += ((x * a[i]) / b[i]) + 1;
			}
			if(cd == c) {
				count++;
			}
			if(cd > c) break;

			x++;
		}

		System.out.println(count);

	}

}


import java.util.Scanner;

public class CF_177E {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt(), c = in.nextInt();
		int[] a = new int[n];
		int[] b = new int[n];

		double sum = 0;
		for(int i = 0; i < n; i++) {
			a[i] = in.nextInt();
			b[i] = in.nextInt();
			sum += a[i] / (double) b[i] + 1;
		}

		if(sum == n) {
			System.out.println("-1");
			return;
		}

		int x = 1;
		int count = 0;
		while(true) {
			int cd = 0;
			for(int i = 0; i < n; i++) {
				cd += ((x * a[i]) / b[i]) + 1;
			}
			if(cd == c) {
				count++;
			}
			if(cd > c) break;

			x++;
		}

		System.out.println(count);

	}

}


//package abbyy2.easy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class ES {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni(), c = ni();
		int[] a = new int[n];
		int[] b = new int[n];
		for(int i = 0;i < n;i++){
			a[i] = ni();
			b[i] = ni();
		}
		int ct = 0;
		for(int x = 1;x <= 10001;x++){
			long s = 0;
			for(int i = 0;i < n;i++){
				s += x*a[i]/b[i] + 1;
			}
			if(s == c){
				ct++;
			}
		}
		out.println(ct);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception
	{
		new ES().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


//package abbyy2.easy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class ES {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni(), c = ni();
		int[] a = new int[n];
		int[] b = new int[n];
		double[] lab = new double[n];
		for(int i = 0;i < n;i++){
			a[i] = ni();
			b[i] = ni();
			if(a[i] == 0){
				lab[i] = Long.MIN_VALUE;
			}else{
				lab[i] = Math.log10(a[i])-Math.log10(b[i]);
			}
		}
		if(n > c){
			out.println(0);
			return;
		}

		long sup = 0;
		{
			long low = 0;
			long high = 1000000000000000001L;
			while(high - low > 1){
				long x = (high+low)/2;
				long s = 0;
				if(x == 0){
					s = n;
				}else{
					double lx = Math.log10(x);
					for(int i = 0;i < n;i++){
						if(lx+lab[i] > 9.3){
							s = Integer.MAX_VALUE;
							break;
						}
						s += x*a[i]/b[i]+1;
						if(s > c)break;
					}
				}
				if(s > c){
					high = x;
				}else{
					low = x;
				}
			}
			sup = low;
		}

		long inf = 0;
		{
			long low = 0;
			long high = 1000000000000000001L;
			while(high - low > 1){
				long x = (high+low)/2;
				long s = 0;
				if(x == 0){
					s = n;
				}else{
					double lx = Math.log10(x);
					for(int i = 0;i < n;i++){
						if(lx+lab[i] > 9.3){
							s = Integer.MAX_VALUE;
							break;
						}
						s += x*a[i]/b[i]+1;
						if(s > c)break;
					}
				}
				if(s >= c){
					high = x;
				}else{
					low = x;
				}
				inf = high;
			}
		}
		if(inf == 1 && n == c)inf = 0;
		tr(sup, inf);
		out.println(sup-inf+1);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception
	{
		new ES().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


package abbyy2.easy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class ES {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni(), c = ni();
		int[] a = new int[n];
		int[] b = new int[n];
		for(int i = 0;i < n;i++){
			a[i] = ni();
			b[i] = ni();
		}
		int ct = 0;
		for(int x = 1;x <= 10001;x++){
			long s = 0;
			for(int i = 0;i < n;i++){
				s += x*a[i]/b[i] + 1;
			}
			if(s == c){
				tr("x", x);
				ct++;
			}
		}
		out.println(ct);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception
	{
		new ES().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

import static java.lang.Math.*;

public class E implements Runnable{

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException{
        if (ONLINE_JUDGE){
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException{
        while(!tok.hasMoreTokens()){
            try{
                tok = new StringTokenizer(in.readLine());
            }catch (Exception e){
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException{
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException{
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException{
        return Double.parseDouble(readString());
    }

    public static void main(String[] args){
        new Thread(null, new E(), "", 256 * (1L << 20)).start();
    }

    long timeBegin, timeEnd;

    void time(){
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory(){
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
    }

    void debug(Object... objects){
        if (DEBUG){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    public void run(){
        try{
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            time();
            memory();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    boolean DEBUG = false;

    void solve() throws IOException{
        int n = readInt();
        int c = readInt();

        int[] a = new int[n];
        int[] b = new int[n];

        double sum = 0;

        for (int i = 0; i < n; i++){
            a[i] = readInt();
            b[i] = readInt();

            sum += a[i];
        }

        c -= n;

        if (c == 0 && sum == 0){
            out.print(-1);
            return;
        }

        double[] up = new double[n];
        double[] down = new double[n];

        for (int i = 0; i < n; i++){
            up[i] = a[i];
            down[i] = sum * b[i];
        }

        long left = 0;
        long right = (long) (1e18);

        for (int it = 0; it < 100; it++){
            long x = (left + right) / 2;

            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res < c){
                left = x + 1;
            }else{
                right = x;
            }
        }

        if (left > right){
            out.print(0);
            return;
        }

        long count = 1;
        long last = left;

        for (long x = left - 1; x >= max(0, last - 100000); x--){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        last = left;

        for (long x = left + 1; x < last + 100000; x++){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        out.print(count);
    }
}


import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

import static java.lang.Math.*;

public class E implements Runnable{

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException{
        if (ONLINE_JUDGE){
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException{
        while(!tok.hasMoreTokens()){
            try{
                tok = new StringTokenizer(in.readLine());
            }catch (Exception e){
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException{
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException{
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException{
        return Double.parseDouble(readString());
    }

    public static void main(String[] args){
        new Thread(null, new E(), "", 256 * (1L << 20)).start();
    }

    long timeBegin, timeEnd;

    void time(){
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory(){
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
    }

    void debug(Object... objects){
        if (DEBUG){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    public void run(){
        try{
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            time();
            memory();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    boolean DEBUG = false;

    void solve() throws IOException{
        int n = readInt();
        int c = readInt();

        int[] a = new int[n];
        int[] b = new int[n];

        double sum = 0;

        for (int i = 0; i < n; i++){
            a[i] = readInt();
            b[i] = readInt();

            sum += a[i];
        }

        c -= n;

        if (c == 0 && sum == 0){
            out.print(-1);
            return;
        }

        double[] up = new double[n];
        double[] down = new double[n];

        for (int i = 0; i < n; i++){
            up[i] = a[i];
            down[i] = sum * b[i];
        }

        long left = 0;
        long right = (long) (1e18);

        for (int it = 0; it < 100; it++){
            long x = (left + right) / 2;

            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res < c){
                left = x + 1;
            }else{
                right = x;
            }
        }

        if (left > right){
            out.print(0);
            return;
        }

        long count = 1;
        long last = left;

        for (long x = left - 1; x >= max(0, last - 10000); x--){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        last = left;

        for (long x = left + 1; x < last + 10000; x++){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        out.print(count);
    }
}


import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

import static java.lang.Math.*;

public class E implements Runnable{

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException{
        if (ONLINE_JUDGE){
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException{
        while(!tok.hasMoreTokens()){
            try{
                tok = new StringTokenizer(in.readLine());
            }catch (Exception e){
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException{
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException{
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException{
        return Double.parseDouble(readString());
    }

    public static void main(String[] args){
        new Thread(null, new E(), "", 256 * (1L << 20)).start();
    }

    long timeBegin, timeEnd;

    void time(){
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory(){
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
    }

    void debug(Object... objects){
        if (DEBUG){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    public void run(){
        try{
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            time();
            memory();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    boolean DEBUG = false;

    void solve() throws IOException{
        int n = readInt();
        int c = readInt();

        int[] a = new int[n];
        int[] b = new int[n];

        double sum = 0;

        for (int i = 0; i < n; i++){
            a[i] = readInt();
            b[i] = readInt();

            sum += a[i];
        }

        c -= n;

        if (c == 0 && sum == 0){
            out.print(-1);
            return;
        }

        double[] up = new double[n];
        double[] down = new double[n];

        for (int i = 0; i < n; i++){
            up[i] = a[i];
            down[i] = sum * b[i];
        }

        long left = 0;
        long right = (long) (1e18);

        for (int it = 0; it < 100; it++){
            long x = (left + right) / 2;

            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res < c){
                left = x + 1;
            }else{
                right = x;
            }
        }

        if (left > right){
            out.print(0);
            return;
        }

        long count = 0;
        long last = left;

        for (long x = left; x >= max(0, last - 100000); x--){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        last = left;

        for (long x = left + 1; x < last + 100000; x++){
            long res = 0;
            for (int i = 0; i < n; i++){
                res += a[i] * x / b[i];
            }

            if (res == c){
                count++;
                last = x;
            }
        }

        out.print(count);
    }
}