#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define PI acos(-1)
typedef  long long ll;
ll gcd(ll x,ll y){
   if(y==0) return x;
   else return gcd(y,x%y);
}
ll lcm(ll x,ll y){
   return x/gcd(x,y)*y;
}

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

   vector<int> a(n);
   rep(i,n){
      cin>>a[i];
   }
   sort(a.begin(),a.end());
   vector<int> b;
   b.push_back(0);
   b.push_back(0);
   rep(i,n-1){
      if(a[i+1]==a[i]){
         if(a[i+2]==a[i]){
            if(a[i+3]==a[i]){
               b.push_back(a[i]);
               b.push_back(a[i]);
               i+=3;
            }
            else{
               b.push_back(a[i]);
               i+=2;
            }
         }
         else{
         b.push_back(a[i]);
         }
      }
   }
   int p=0,q=0;

   sort(b.begin(),b.end(),greater<int>());
   cout<<(ll)b[0]*(ll)b[1];

   return 0;
}

// g++ A.cpp -Wall -Wextra -Woverflow -Wshadow -O2
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <vector>
#include <cstring>
#include <climits>
#include <queue>
#include <cmath>
#include <iomanip>
#include <set>
#include <bitset>

using namespace std;

typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> edge;

const int MAXN = 2 * 100005;
int n;
LL a[MAXN];
LL pref[MAXN];
LL get(int a, int b) {
  return pref[b] - pref[a - 1];
}
int find(int L, int R) {
  int b1 = L, b2 = R;
  while (L + 1 < R) {
    int mid = (L + R) / 2;
    LL v1 = get(b1, mid);
    LL v2 = get(mid + 1, b2);
    if (v1 < v2) {
      L = mid;
    } else if (v1 > v2) {
      R = mid;
    } else {
      L = mid;
      R = mid;
      break;
    }
  }
  if (abs(get(b1, L) - get(L + 1, b2)) < abs(get(b1, R) - get(R + 1, b2))) {
    return L;
  }
  return R;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    pref[i] = pref[i - 1] + a[i];
  }
  LL ans = LLONG_MAX;
  for (int i = 2; i <= n - 2; i++) {
    int L = find(1, i);
    int R = find(i + 1, n);
    LL B = get(1, L);
    LL C = get(L + 1, i);
    LL D = get(i + 1, R);
    LL E = get(R + 1, n);
    LL diff = max(B, max(C, max(D, E))) - min(B, min(C, min(D, E)));
    ans = min(ans, diff);
  }
  cout << ans << endl;
}


#include <bits/stdc++.h>
using namespace std;
#define maxn 1000010
#define ll long long
#define db double
#define vi vector<int>
#define pb push_back
#define mod 998244353
ll ksm(ll a, ll b) {
   if (!b) return 1;
   ll ns = ksm(a, b >> 1);
   ns = ns * ns % mod;
   if (b & 1) ns = ns * a % mod;
   return ns;
}
// head
vi pl[26];
int ff[maxn];
int lb(int a) {
	return a & -a;
}
int d[maxn];
int q(int pl) {
	int ans = 0;
	while (pl) {
		ans = max(ans, d[pl]);
		pl -= lb(pl);
	}
	return ans;
}
void upd(int pl, int num) {
	while (pl < maxn) {
		d[pl] = max(d[pl], num);
		pl += lb(pl);
	}
}
char s[maxn], t[maxn];
int main() {
	int n;
	cin >> n;
	scanf("%s", s);
	scanf("%s", t);
	for (int i = 0; i < n; i++)
		pl[s[i] - 'a'].pb(i);
	int fl = 1;
	for (int i = 0; i < n; i++)
		if (s[i] != t[i]) fl = 0;
	if (fl) {
		cout << 0 << endl;
		return 0;
	}
	int nx = maxn;
	for (int i = n - 1; i >= 0; i--) {
		if (i && t[i] == t[i - 1]) continue;
		int ed = min(i + 1, nx); // <= i < nx
		int x = lower_bound(pl[t[i] - 'a'].begin(), pl[t[i] - 'a'].end(), ed) - pl[t[i] - 'a'].begin();//lower_bound(p

		if (!x) {
			printf("-1\n");
			return 0;
		}
		x--;
		ff[i] = pl[t[i] - 'a'][x], nx = ff[i];
	//	cout << i << ' ' << x << ' ' << ff[i] << endl;
	}
	vi s;
	int cnt = 0;
	int ans = 0;
	for (int i = 0; i < n; i++) {
		if (i && t[i] == t[i - 1]) continue;
		cnt++;
		int bg = i - cnt;
		s.pb(bg);
		int uu = ff[i] - cnt;
		int nans = upper_bound(s.begin(), s.end(), uu) - s.begin();
		ans = max(ans, cnt - nans);
	}
	ans++;
	cout << ans << endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
int n,offset,j,pre,ans;
string s,t;
deque<int> q;
int main()
{
	cin>>n>>s>>t;
	q.push_back(n);j=n-1;
	for (int i=n-1;i>=0;i--)
	{
		pre=j;
		while(j>=0 && (j>i || s[j]!=t[i])) j--;
		if (j<0)
		{
			printf("-1\n");
			return 0;
		}
		if (pre==j)
		{
			while(!q.empty() && q.back()-offset>=i) q.pop_back();
			q.push_back(i+offset);
 		}
 		else
 		{
 			offset++;
 			if (i!=j)
 			{
 				ans=max(ans,(int)q.size());
 				q.push_front(j+offset);
			 }
		}
	}
	cout<<ans<<endl;
	return 0;
}


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

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
#define fast ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define ll long long
#define int long long
#define vll vector<long long>
#define pii pair<long long ,long long >
#define vvi vector< vector<long long > >
#define vpii vector<pair<int,int>>
#define pll  pair<long long ,long long >
#define pb  push_back
#define ff  first
#define sec second
#define SORT(a) sort(a.begin(),a.end())
#define SORTR(a) sort(a.rbegin(),a.rend())
#define m_p make_pair
#define all(x) (x.begin(),x.end())
#define sz(v) ((int)(v.size()))
#define endl '\n'
typedef vector< long long > vi ;
const int MOD = 1e9 + 7 ;
int size = 10000000;

void solve() {

	int a, b; cin >> a >> b;
	cout << a*b << endl;

}

int32_t main() {
	fast;
	/*#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
	#endif
	*/
	int T = 1; //cin>>T;
	while (T--) {
		solve();
	}

	return 0;
}

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <random>
#include <vector>
#include <array>
#include <bitset>
#include <queue>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>

using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;

int main() {

   int a,b,c;
   cin >> a >> b >> c;
   swap(a, b);
   swap(a, c);
    cout << a << " " << b << " " << c;
    return 0;
}


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

#define REP(i,m,n) for(int i=(m); i<(int)(n); i++)
#define RREP(i,m,n) for(int i=(int)((n)-1); i>=m; i--)
#define rep(i,n) REP(i,0,n)
#define rrep(i,n) RREP(i,0,n)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define fi first
#define se second
#define debug(...) {cerr<<"[L"<<__LINE__<<"] "; _debug(__VA_ARGS__);}

template<typename T>
string join(const vector<T>&v, string del=", "){ stringstream s;
    for(auto x : v) s << del << x; return s.str().substr(del.size());
}
template<typename T>
ostream& operator<<(ostream& o, const vector<T>&v){
    if(v.size()) o << "[" << join(v) << "]"; return o;
}
template<typename T>
ostream& operator<<(ostream& o, const vector<vector<T> >&vv){
    int l = vv.size();
    if(l){ o<<endl; rep(i,l) o << (i==0 ? "[ " : ",\n  " ) << vv[i] << (i==l-1 ? " ]" : ""); }
    return o;
}
template<typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2>& p){
    return o << "(" << p.first << ", " << p.second << ")";
}
inline void _debug(){cerr<<endl;}
template<class First, class... Rest>
void _debug(const First& first, const Rest&... rest){cerr<<first<<" ";_debug(rest...);}

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;

const double PI = (1*acos(0.0));
const double EPS = 1e-9;
const int INF = 0x3f3f3f3f;
const ll INFL = 0x3f3f3f3f3f3f3f3fLL;
const ll mod = 1e9 + 7;

inline void finput(string filename) {
    freopen(filename.c_str(), "r", stdin);
}

int main(){
    ios_base::sync_with_stdio(0);
    // finput("./input");
    int n; cin >> n;
    vi a(n);
    rep(i,n) cin >> a[i];
    sort(all(a));

    map<int,vi> mp;
    rep(i,n) mp[a[i]].push_back(i);
    vi used(n,0);
    int ans = 0;
    rrep(i,n){
        if(used[i]) continue;
        int lsb = __builtin_ffsll(a[i]) - 1;
        int msb = (31 - __builtin_clz(a[i]));
        int x = 1 << lsb;
        REP(j,lsb,msb){
            if((a[i]&(1<<j)) == 0) x |= 1<<j;
        }
        if(mp.count(x)){
            if(mp[x].size() == 0) continue;
            if(mp[x].back() == i){
                mp[x].pop_back();
                if(mp[x].size() == 0) continue;
            }
            int idx = mp[x].back();
            used[idx] = 1;
            mp[x].pop_back();
            ans++;
        }
    }
    cout << ans << endl;
    return 0;
}

//q098.cpp
//Wed Sep 16 20:16:46 2020

#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#define INTINF 2147483647
#define LLINF 9223372036854775807
#define MOD 1000000007
#define rep(i,n) for (int i=0;i<(n);++i)

using namespace std;
using ll=long long;
typedef pair<int,int> P;

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

	ll ans = 1;
	vector<int> count(3,0);
	rep(i,n){
		ll a;
		cin >> a;
		ll tmp = 0;
		ll flag = 1;
		rep(j,3){
			if(count[j]==a){
				tmp++;
				if(flag){
					count[j]++;
					flag = 0;
				}
			}
		}
		ans = ans*tmp%MOD;
	}

	cout << ans << endl;
//	printf("%.4f\n",ans);
}


#include <bits/stdc++.h>
using namespace std;
//#include <atcoder/all>
//using namespace atcoder;
template <typename T> bool chmax(T &u, const T z) { if (u < z) {u = z; return true;} else return false; }
template <typename T> bool chmin(T &u, const T z) { if (u > z) {u = z; return true;} else return false; }
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
#define ll long long
typedef pair<ll, ll> P;
const ll INF = 1LL << 60;
//const int MOD = 1000000007;
const ll MOD=998244353;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }

int main(){
  string s;
  cin>>s;
  int n=s.size();
  rep(i,n-1){
    string t=s.substr(i,2);
    if(t=="AC"){
      cout<<"Yes"<<endl;
      return 0;
    }
  }
  cout<<"No"<<endl;
  return 0;
}

#include <iostream>
using namespace std;

int main()
{
  string test;
  getline(cin,test);

  if (test[0] == 'A' && test[1] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[1] == 'A' && test[2] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[2] == 'A' && test[3] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[3] == 'A' && test[4] == 'C')
  {
    cout << "Yes" << endl;
  }
  else
  cout << "No" << endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
typedef long double ld;
const int inf=1e9+7;
const ll longinf=1LL<<60;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
#define F first
#define S second

const int mx=200010;
const ll mod=1e9+7;

int main(){
  int a,b;
  cin >> a >> b;
  vector<vector<char>> data(100, vector<char>(100,'.'));
  rep(i,50)rep(j,100){ data[i][j]='#'; }
  int cnt=a-1;
  rep(i,25)rep(j,50)if(cnt){ data[i*2][j*2]='.'; cnt--;}
  cnt=b-1;
  rep(i,25)rep(j,50)if(cnt){ data[51+i*2][j*2]='#'; cnt--;}

  cout << 100 << " " << 100 << endl;
  rep(i,100){ rep(j,100){ cout << data[i][j]; }  cout<<endl; }
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<ll,ll> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
#define M 1000000007
#define all(a) (a).begin(),(a).end()
#define rep(i,n) reps(i,0,n)
#define reps(i,m,n) for(int i=(m);i<(n);i++)
int main(){
  ll n,k;cin>>n>>k;
  vector<ll> a(n),b(k);
  rep(i,n)cin>>a[i];
  rep(i,k)cin>>b[i];
  ll c=0LL,d=0LL;
  ll j=-n+1;
  rep(i,n){
    c+=a[i]*j;
    j+=2;
  }
  j=-k+1;
  rep(i,k){
    d+=b[i]*j;
    j+=2;
  }
  cout<<(c%M)*(d%M)%M;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned ui;
typedef unsigned long long ul;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pdd;
typedef pair<bool, bool> pbb;
typedef vector<int> vi;
#define pb push_back
#define fi first
#define se second
#define mid ((l + r) >> 1)
#define ls (i << 1)
#define rs (i << 1 | 1)
#define enum(i, j, k) for(int i = j; i <= (k); i ++)
#define open(i, j, k) for(int i = j; i <  (k); i ++)
#define dec(i, j, k)  for(int i = j; i >= (k); i --)
#define fill(x, k) memset(x, k, sizeof x)
#define copy(x, y) memcpy(x, y, sizeof x)
#define fio(x) freopen(x".in", "r", stdin); freopen(x".out", "w", stdout);
template <class T> bool chkmin(T &x, T y)
{ return y < x ? (x = y , true) : false; }
template <class T> bool chkmax(T &x, T y)
{ return y > x ? (x = y , true) : false; }
struct __init { __init()
{
	ios::sync_with_stdio(false); cin.tie(0);
	cout.precision(16); cout << fixed;
	srand(time(0) ^ ui(ul(new char)));
}};
static __init __init__;
/* default code ends here */
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int n, m;
ll a[maxn], b[maxn];
int main()
{
	cin >> n >> m;
	enum(i, 1, n)
		cin >> a[i];
	enum(i, 1, m)
		cin >> b[i];
	ll s1 = 0, s2 = 0;
	enum(i, 1, n - 1)
		s1 = (s1 + (a[i + 1] - a[i]) * i % mod * (n - i)) % mod;
	enum(i, 1, m - 1)
		s2 = (s2 + (b[i + 1] - b[i]) * i % mod * (m - i)) % mod;
	cout << s1 * s2 % mod << '\n';
	return 0;
}


#include <iostream>
#include <math.h>

using namespace std;

class point{
public:
	double x, y;
	int set();
};

int point::set()
{
	cin >> x >> y;
	return 0;
}

int main()
{
	point P1, P2;
	P1.set();
	P2.set();

	cout << fixed << sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y)) << endl;

	return 0;
}

#include <iostream>
#include <cmath>
#include <cstdio>

int main()
{
    using namespace std;

    double x1, x2, y1, y2;
    double dis;

    cin >> x1 >> y1 >> x2 >> y2;

    dis = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    printf("%.8lf\n", dis);

    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <queue>
#include <bitset>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define mp make_pair
#define all(a) begin(a),end(a)
#define FOR(x,val,to) for(int x=(val);x<int((to));++x)
#define FORE(x,val,to) for(auto x=(val);x<=(to);++x)
#define FORR(x,arr) for(auto &x: arr)
#define FORS(x,plus,arr) for(auto x = begin(arr)+(plus); x != end(arr); ++x)
#define FORREV(x,plus,arr) for(auto x = (arr).rbegin()+(plus); x !=(arr).rend(); ++x)
#define REE(s_) {cout<<s_<<'\n';exit(0);}
#define GET(arr) for(auto &i: (arr)) sc(i)
#define whatis(x) cerr << #x << " is " << x << endl;
#define e1 first
#define e2 second
#define INF 0x7f7f7f7f
typedef std::pair<int,int> pi;
typedef std::vector<int> vi;
typedef std::vector<std::string> vs;
typedef int64_t ll;
typedef uint64_t ull;
#define umap unordered_map
#define uset unordered_set
using namespace std;
using namespace __gnu_pbds;

#ifdef _WIN32
#define getchar_unlocked() _getchar_nolock()
#define _CRT_DISABLE_PERFCRIT_LOCKS
#endif
template<class T> ostream& operator<<(ostream &os, set<T> V) { os<<"[";for(auto const &vv:V)os<<vv<<","; os<<"]"; return os; }
template<class T> ostream& operator<<(ostream &os, vector<T> V) { os<<"[";for(auto const &vv:V)os<<vv<<","; os<<"]"; return os; }
template<class L, class R> ostream& operator<<(ostream &os, pair<L, R> P) { os<<"("<<P.first<<","<<P.second<<")"; return os; }
inline int fstoi(const string &str){auto it=str.begin();bool neg=0;int num=0;if(*it=='-')neg=1;else num=*it-'0';++it;while(it<str.end()) num=num*10+(*it++-'0');if(neg)num*=-1;return num;}
inline void getch(char &x){while(x = getchar_unlocked(), x < 33){;}}
inline void getstr(string &str){str.clear(); char cur;while(cur=getchar_unlocked(),cur<33){;}while(cur>32){str+=cur;cur=getchar_unlocked();}}
template<typename T> inline bool sc(T &num){ bool neg=0; int c; num=0; while(c=getchar_unlocked(),c<33){if(c == EOF) return false;} if(c=='-'){ neg=1; c=getchar_unlocked(); } for(;c>47;c=getchar_unlocked()) num=num*10+c-48; if(neg) num*=-1; return true;}template<typename T, typename ...Args> inline void sc(T &num, Args &...args){ bool neg=0; int c; num=0; while(c=getchar_unlocked(),c<33){;} if(c=='-'){ neg=1; c=getchar_unlocked(); } for(;c>47;c=getchar_unlocked()) num=num*10+c-48; if(neg) num*=-1; sc(args...); }
template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //s.find_by_order(), s.order_of_key() <- works like lower_bound
template<typename T> using ordered_map = tree<T, int, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

bool srt(pi a, pi b){
    return a.e1+a.e2 < b.e1+b.e2;
}

int main(){
    ios_base::sync_with_stdio(0);cin.tie(0);
    int n;
    sc(n);
    pi a[n];
    FORR(i,a)
        sc(i.e1,i.e2);
    sort(a,a+n,srt);
    ll dp[n+1];
    ll LINF = 1e18;
    FORR(i,dp)
        i = LINF;
    dp[0] = 0;
    FORR(i,a){
        /* whatis(i) */
        for(int x = n-1; x >= 0; --x){
            /* whatis(x) */
            /* whatis(dp[x]) */
            if(dp[x] == LINF) continue;
            if(dp[x] > i.e1) continue;
            /* if(dp[ */
            dp[x+1] = min(dp[x+1],dp[x]+i.e2);
        }
    }
    for(int i = n+1; --i;)
        if(dp[i] != LINF) REE(i)
}

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)

using namespace std;
typedef long long int ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> PI;
typedef pair<ll, ll> PL;

struct cmp {
  bool operator()(PL x, PL y) const {
    if (x.first <= y.first && x.second <= y.second) {
      return x != y;
    }
    if (x.first >= y.first && x.second >= y.second) {
      return false;
    }
    bool flip = false;
    if (x > y) {
      swap(x, y);
      flip = true;
    }
    bool ans = false;
    // x.0 <= y.0, x.1 >= y.1
    if (x.first >= y.second) {
      ans = false;
    } else {
      ans = true;
    }
    if (flip) ans = !ans;
    return ans;
  }
};

const ll inf = 1e16;

int main(void) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  VL h(n), p(n);
  vector<PL> pool;
  vector<VL> dp(n + 1, VL(n + 1, inf));
  REP(i, 0, n) {
    cin >> h[i] >> p[i];
    pool.push_back(PL(h[i]+p[i], p[i]));
  }
  sort(pool.begin(), pool.end());
  dp[0][0] = 0;
  REP(i, 0, n) {
    ll y = pool[i].second;
    ll x = pool[i].first - y;
    REP(j, 0, i + 2) {
      dp[i + 1][j] = dp[i][j];
      if (j >= 1 && dp[i][j - 1] <= x) {
	dp[i + 1][j] = min(dp[i + 1][j], dp[i][j - 1] + y);
      }
    }
  }
  int ma = 0;
  REP(i, 0, n + 1) {
    if (dp[n][i] < inf) {
      ma = max(ma, i);
    }
  }
  cout << ma << "\n";
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<cmath>
using namespace std;

int main(){
    long long N;
    long long travel[5];
    cin >> N;
    for (int i = 0; i < 5; i++){
        cin >> travel[i];
    }
    sort(travel, travel + 5);
    cout << 4 + (N + travel[0] - 1)/ travel[0] << endl;

    return 0;
}

#include<stdio.h>

#define INFTY 2000000000

long long count = 0;

void merge(int A[], int left, int mid, int right) {
  int n1 = mid - left;
  int n2 = right - mid;
  int L[n1+1], R[n2+1];
  for (int i = 0; i < n1; i++) L[i] = A[left + i];
  for (int i = 0; i < n2; i++) R[i] = A[mid + i];
  L[n1] = INFTY;
  R[n2] = INFTY;
  int i = 0, j = 0;
  for (int k = left; k < right; k++) {
    if (L[i] <= R[j]) {
      A[k] = L[i];
      i++;
    } else {
      A[k] = R[j];
      count += n1 - i;
      j++;
    }
  }
}

void mergeSort(int A[], int left, int right) {
  if (left+1 < right) {
    int mid = (left + right)/2;
    mergeSort(A, left, mid);
    mergeSort(A, mid, right);
    merge(A, left, mid, right);
  }
}

int main() {
	int n;
  scanf("%d", &n);
  int S[n];
  for ( int i = 0; i < n; i++ ) scanf("%d", &S[i]);
  mergeSort(S, 0, n);
  printf("%llu\n", count);

  return 0;
}


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

using ll = long long;
using ull = unsigned long long;
using ld = long double;

#define MOD 1000000007LL

#define rep(i, n) for(ll (i) = 0LL;(i) < (ll)(n);(i)++)
#define rep2(i, s, e) for(ll (i) = (ll)(s);(i) < (ll)(e);(i)++)
#define repi(i, n) for(ll (i) = 0LL;(i) <= (ll)(n);(i)++)
#define repi2(i, s, e) for(ll (i) = (ll)(s);(i) <= (ll)(e);(i)++)
#define per(i, n) for(ll (i) = (ll)(n) - 1LL;(i) >= 0LL;(i)--)
#define per2(i, s, e) for(ll (i) = (ll)(s) - 1LL;(i) >= (ll)(e);(i)--)
#define peri(i, n) for(ll (i) = (ll)(n);(i) >= 0LL;(i)--)
#define peri2(i, s, e) for(ll (i) = (ll)(s);(i) >= (ll)(e);(i)--)
#define iter(i, it) for(auto &(i): (it))

template<typename T, typename U> ostream& operator<<(ostream &s, const pair<T, U> m) {
    cout << "(" << m.first << ", " << m.second << ")";
    return s;
}
template<typename T, typename U> ostream& operator<<(ostream &s, const map<T, U> m) {
    ll c = 0;
    cout << "{ ";
    iter(i, m) cout << i << (c++ == m.size() - 1 ? " " : ", ");
    cout << "}";
    return s;
}
template<typename T> ostream& operator<<(ostream &s, const vector<T> &v) {
    cout << "{ ";
    rep(i, v.size()) cout << v[i] << (i == v.size() - 1 ? " " : ", ");
    cout << "}";
    return s;
}
template<typename T> ostream& operator<<(ostream &s, const list<T> &v) {
    ll c = 0;
    cout << "{ ";
    iter(i, v) cout << i << (c++ == v.size() - 1 ? " " : ", ");
    cout << "}";
    return s;
}

int main(void) {
    ll N;
    cin >> N;
    vector<pair<ll, pair<ll, ll>>> A;
    rep(i, N) {
        ll a, b;
        cin >> a >> b;
        A.emplace_back(a + b, pair<ll, ll>{a, b});
    }
    sort(A.rbegin(), A.rend());
    ll a = 0, b = 0;
    rep(i, A.size()) {
        if(i % 2) b += A[i].second.second;
        else a += A[i].second.first;
    }
    cout << a - b << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;

#define int ll
#define REP(i,n) for (int i = 0; i < (n); ++i)
#define FORE(i, s, n) for (int i = (s); i <= (int)(n); i++)

#define ALL(vec) (vec).begin(), (vec).end()
#define REVALL(vec) (vec).rbegin(), (vec).rend()

#define debug(x) cerr << #x << ": " << x << '\n'
#define hyphen() cerr << "--\n"

#define fst first
#define pb push_back

const int MOD = (int)1e9 + 7;

int bigger(int a, int b) {
    return a >= b ? a : b;
}

int smaller(int a, int b) {
    return a >= b ? b : a;
}

signed main() {
    int N;

    cin >> N;

    vector<int> As(N);
    vector<int> Bs(N);
    REP(i, N) {
        cin >> As.at(i) >> Bs.at(i);
    }

    // (priority, score, ind)
    vector<tuple<int, int, int>> sorted_for_a(N);
    vector<tuple<int, int, int>> sorted_for_b(N);
    REP(i, N) {
        int a = As.at(i);
        int b = Bs.at(i);
        int priority = a + b;
        tuple<int, int, int> ta = make_tuple(priority, a, i);
        tuple<int, int, int> tb = make_tuple(priority, b, i);

        sorted_for_a.pb(ta);
        sorted_for_b.pb(tb);
    }

    sort(REVALL(sorted_for_a));
    sort(REVALL(sorted_for_b));

    queue<tuple<int, int, int>> a_queue;
    for (auto a : sorted_for_a) {
        a_queue.push(a);
    }

    queue<tuple<int, int, int>> b_queue;
    for (auto b : sorted_for_b) {
        b_queue.push(b);
    }

    // それが食べられたことを表す配列
    vector<bool> eaten(N, false);

    // ここから作業開始
    int score_a = 0;
    int score_b = 0;

    tuple<int,int,int> ta;
    tuple<int,int,int> tb;

    while(!a_queue.empty() || !b_queue.empty()) {
        // Aのターン

        // 食べられていない料理が見つかるまで捨てる
        while(true) {
            if (a_queue.empty()) {
                break;
            }

            ta = a_queue.front();
            a_queue.pop();

            int& ind = get<2>(ta);
            if (!eaten.at(ind)) {
                break;
            }
        }

        if (a_queue.empty()) {
            break;
        }

        // Aが食べる処理
        int& a = get<1>(ta);
        int& ind_a = get<2>(ta);
        debug(a);
        debug(ind_a);

        score_a += a;
        debug(ind_a);
        eaten.at(ind_a) = true;

        // 食べられていない料理が見つかるまで捨てる
        while(true) {
            if (b_queue.empty()) {
                break;
            }

            tb = b_queue.front();
            b_queue.pop();

            int& ind = get<2>(tb);
            if (!eaten.at(ind)) {
                break;
            }
        }

        // Bが食べる処理
        // 後攻はもう食べるものが無い可能性がある
        if (b_queue.empty()) {
            break;
        }

        int& b = get<1>(tb);
        int& ind_b = get<2>(tb);
        debug(b);
        debug(ind_b);

        score_b += b;
        debug(ind_b);
        eaten.at(ind_b) = true;
    }

    cout << score_a - score_b << endl;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <algorithm>
#include <functional>

using namespace std;

#define rep(i,n) for((i)=0;(i)<(int)(n);(i)++)
#define foreach(itr,c) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
/*
vector<string> split(string& s, char x){ // O(s.length())
  int i;
  vector<string> res(1);

  int word = 0;
  rep(i,s.size()){
    if(s[i] != x) res[word].push_back(s[i]);
    else if(i != 0 && i != s.size()-1){
      word++;
      res.push_back("");
    }
  }

  return res;
}
*/
int main(){
  int i,j,N;

  scanf("%d\n",&N);
  rep(i,N){
    string in;
    getline(cin,in);
/*
    vector<string> sp = split(in,' ');
    rep(j,sp.size()){
      if(sp[j] == "Hoshino") sp[j] = "Hoshina";
      if(sp[j] == "Hoshino.") sp[j] = "Hoshina.";
      cout << sp[j];
      if(j != sp.size()-1) cout << ' '; else cout << endl;
    }
  */
    int found = -1;
    while((found = in.find("Hoshino")) != -1) in[found + 6] = 'a';
    cout << in << endl;
  }

  return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)

int main(void){
    int n;
    string h = "Hoshino";
    string s;
    cin >> n;
    getline(cin, s);
    stringstream ss(s);
    ss >> n;
    rep(loop, n) {
        getline(cin, s);
        rep(i, s.size()){
            if(i+h.size()-1 >= s.size()) break;
            bool same = true;
            rep(j, h.size()) {
                if(s[i+j]!=h[j]) {
                    same = false;
                    break;
                }
            }
            if(same) s[i+h.size()-1] = 'a';
        }
        cout << s << endl;
    }
}


#include<iostream>
#include<cstring>
using namespace std;

int main()
{
  int n,m;
  for(;cin>>n>>m;)
    {
      int a[n];
      for(int i=0;i<n;i++)
	cin>>a[i];
      int cnt[n];
      int ans=0;
      int anscnt=0;
      memset(cnt,0,sizeof(cnt));
      for(int i=0;i<m;i++)
	{
	  int b;
	  cin>>b;
	  for(int j=0;j<n;j++)
	    {
	      if(a[j]<=b)
		{
		  cnt[j]++;
		  if(cnt[j]>anscnt)
		    {
		      anscnt=cnt[j];
		      ans=j+1;
		    }
		  break;
		}
	    }
	}
      cout<<ans<<endl;
    }
}

//
//  main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main(){
	int n,m;
	int A[1001]={},B[1001]={};
	vector<pair<int,int> > vec;

	cin >> n >> m;
	for(int i=0;i<n;i++){
		cin >> A[i];
//		vec.push_back(make_pair(A[i],i));
	}
	for(int i=0;i<m;i++){
		cin >> B[i];
	}

//	sort(vec.begin(),vec.end(),greater<pair<int,int> >());
	int answer[1001]={};

	for(int j=0;j<m;j++){
		for(int i=0;i<n;i++){
			if(A[i] <= B[j]){
				answer[i] ++;
				break;
			}
		}
	}
	int Max = -1;
	for(int i=0;i<n;i++){
		Max = max(Max,answer[i]);
	}
	for(int i=0;i<n;i++){
		if(Max == answer[i]){
			cout << i+1 << endl;
			break;
		}
	}

	return 0;
}


#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef pair<ll,ll> P;
typedef priority_queue<P,vector<P>,greater<P>> P_queue;

#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
#define mp make_pair
#define ALL(a) a.begin(),a.end()
#define SORT(a) sort(ALL(a))
#define U_ERASE(V) V.erase(unique(ALL(V)), V.end());

const ll MOD=998244353;
const ll mod=1000000007;
const ll INF=1e15;
vec dx={1,0,-1,0};
vec dy={0,1,0,-1};

ll d[401][401];

const ll MAXN=200001;

ll par[MAXN];
ll rnk[MAXN];
ll Size[MAXN];

vec D(MAXN,-1);

ll Co[MAXN][2];

void shoki(){
    for(ll i=0;i<MAXN;i++) {par[i]=i; rnk[i]=0; Size[i]=1;}
}

ll sch(ll x){
    if(par[x]==x) return x;
    else return par[x]=sch(par[x]);
}

void con(ll A,ll B){
    A=sch(A);
    B=sch(B);
    if(A==B) return;
    if(rnk[A]>rnk[B]) swap(A,B);
    par[A]=B;
    Size[B]+=Size[A];
    Size[A]=Size[B];
    if(rnk[A]==rnk[B]) rnk[B]++;

    return;
}

ll is_size(ll k){
    return Size[sch(k)];
}

bool same(ll A,ll B){
    return sch(A)==sch(B);
}

int main(){
    shoki();
    rep(i,401) rep(j,401) d[i][j]=INF;
    ll H,W; cin>>H>>W;
    rep(i,H){
        string S; cin>>S;
        rep(j,W){
            if(S.at(j)=='#') d[i][j]=1;
            else d[i][j]=0;
            D.at(i*450+j)=d[i][j];
        }
    }

    rep(i,H) rep(j,W){
        if(i!=H-1){
            if(d[i][j]!=d[i+1][j]) con(i*450+j,(i+1)*450+j);
        }

        if(j!=W-1){
            if(d[i][j]!=d[i][j+1]) con(i*450+j,i*450+j+1);
        }
    }
    rep(i,H) rep(j,W){
        ll x=i*450+j;
        //cout<<sch(x)<<endl;
        Co[sch(x)][D.at(x)]++;
    }
    ll ans=0;
    rep(i,H) rep(j,W){
        ll x=i*450+j;
       // cout<<Co[x][0]<<' '<<Co[x][1]<<endl;
        ans+=Co[x][0]*Co[x][1];
    }
    cout<<ans<<endl;

}

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
#define equals(a, b) (fabs((a) - (b)) < EPS)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const ll mod = 1000000007;
//const ll mod = 998244353;
const int inf = 1e9 + 10;
const ll INF = 1e18;
const ld EPS = 1e-10;
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

int h, w;
vector<string> s;

vector<int> G[160160];
bool visited[160160];

vector<ll> cnt;

void dfs(int v) {
  if (visited[v]) return;
  visited[v] = true;
  if (s[v / w][v % w] == '#') cnt[0]++;
  else cnt[1]++;
  for (int u: G[v]) {
    dfs(u);
  }
}

int main() {
  cin >> h >> w;
  s.resize(h);
  rep(i, h) cin >> s[i];

  rep(i, h) {
    rep(j, w) {
      rep(k, 4) {
        int ry = i + dy[k], rx = j + dx[k];
        if (ry < 0 || ry >= h || rx < 0 || rx >= w) continue;
        if (s[i][j] != s[ry][rx]) {
          G[i * w + j].push_back(ry * w + rx);
        }
      }
    }
  }
  ll ans = 0;
  rep(i, h) {
    rep(j, w) {
      if (visited[i * w + j]) continue;
      cnt = vector<ll>(2, 0);
      dfs(i * w + j);
      ans += cnt[0] * cnt[1];
    }
  }
  cout << ans << endl;

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<ll, ll> PLL;
#define chmax(x, y) do { x = max(x, y); } while(0)
#define chmin(x, y) do { x = min(x, y); } while(0)
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) \
  for (ll i = static_cast<ll>(a); i < static_cast<ll>(b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, ) (__VA_ARGS__)  // NOLINT
template<typename T>
using reversed_priority_queue = std::priority_queue<T, std::vector<T>, std::greater<T> >;

ll N, Q;
string s;

signed main() {
  cin >> N >> s >> Q;
  while (Q--) {
    ll k;
    cin >> k;
    vector<ll> d(N, 0), m(N, 0), dm(N, 0);
    // d, m, dm の構築
    if (s[0] == 'D') d[0] = 1;
    if (s[0] == 'M') m[0] = 1;
    for (int i = 1; i < N; i++) {
      d[i] = d[i-1];
      m[i] = m[i-1];
      dm[i] = dm[i-1];
      if (s[i] == 'D') {
        d[i] += 1;
      }
      if (s[i] == 'M') {
        m[i] += 1;
        dm[i] += d[i-1];
      }
    }
    ll ans = 0;
    // 集計
    for (int i = 2; i < N; i++) {
      if (s[i] != 'C') continue;
      ans += dm[i-1];
      if (i - k >= 0) {
        ans -= dm[i-k];
        ans -= d[i-k] * (m[i-1] - m[i-k]);
      }
    }
    cout << ans << endl;
  }
  return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define ALL(v) (v).begin(),(v).end()
#define REP(i,p,n) for(int i=p;i<(int)(n);++i)
#define rep(i,n) REP(i,0,n)
#define dump(a) (cerr << #a << "=" << (a) << endl)
#define DUMP(list) cout << "{ "; for(auto nth : list){ cout << nth << " "; } cout << "}" << endl;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

using namespace std;

int N;
string S;
long long m, c, t;

void add(int i) {
    if (S[i] == 'M') ++m;
    else if (S[i] == 'C') ++c, t += m;
}

void erase(int i) {
    if (S[i] == 'M') --m, t -= c;
    else if (S[i] == 'C') --c;
}

long long solve(int K) {
    long long res = 0;
    m = 0; t = 0;
    int r = 0;
    for (int l = 0; l < N;) {
        while(r < N && r - l <K) add(r++);
        if (S[l] == 'D') res += t;
        erase(l++);
    }
    return res;
}

int main(){
    while (cin >> N >> S) {
        int Q; cin >> Q;
        for (int i = 0; i < Q; ++i) {
            int k; cin >> k;
            cout << solve(k) << endl;
        }
    }
}


#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <string>
#include <string.h>
using namespace std;
double PI = 3.1415926535897932;
long mod = 1000000007;

const long INF = 1e9 + 1;

int main() {
  string n;
  cin >> n;

  while(1) {
    if(n[0] == n[1] & n[1] == n[2]){
      cout << n << endl;
      return 0;
    }
    else {
      int t = stoi(n);
      t++;
      n = to_string(t);
    }
  }
}

#include <string>
#include <iostream>

using namespace std;

string reverse_seq(string str)
{
	string str_ = "";

	for(string::size_type i = 0; i < str.size(); i++)
	{
		str_ = str[i] + str_;
	}

	return str_;
}

int main()
{
	string str;

	cin>>str;

	cout << reverse_seq(str) << endl;
}


#include <iostream>
#include <vector>
#include <set>
using namespace std;

#define rep(i,n) for(i = 0;i < n;++i)

template <typename T>
struct RUQ //calculateはminimum
{
    int n;
    const T ex = 1 << 30; //dat 初期値(minなので)
    const T em = 1 << 30; //lazy 初期値(minなので)
    vector<T> dat, lazy; //tree本体
    RUQ(vector<T> v){
        int x = 1;
        int i;
        n = v.size();
        while(x < n) x <<= 1;
        n = x;
        dat.resize(2*n-1, ex);
        lazy.resize(2*n-1, em);
        for(i = 0;i < v.size();++i){
            dat[i + n - 1] = v[i];
        }
        for(i = n-2;i >= 0;--i){
            dat[i] = calculate(dat[2*i+1], dat[2*i+2]);
        }
    }

    T calculate(T a, T b){
        return min(a, b); //minで使う
    }

    void eval(int now){
        if(lazy[now] == em) return;
        if(now < n - 1){ //最小値なのでそのまま代入
            lazy[2*now + 1] = lazy[now];
            lazy[2*now + 2] = lazy[now];
        }
        dat[now] = lazy[now];
        lazy[now] = em;
    }

    void update(int a, int b, T x, int now, int l, int r){
        eval(now);
        if(a <= l && r<= b){
            lazy[now] = x; //上から書き換える。最小値なので代入する
            eval(now);
        }else if(a < r && l < b){
            update(a, b, x, 2*now + 1, l, (l + r)/2);
            update(a, b, x, 2*now + 2, (l + r)/2, r);
            dat[now] = calculate(dat[2*now + 1], dat[2*now + 2]);
        }
    }
    void update(int a, int b, T x){update(a, b, x, 0, 0, n);}

    T query(int a, int b){return query_sub(a, b, 0, 0, n);}
    T query_sub(int a, int b, int now, int l, int r){
        eval(now);
        if(r <= a || b <= l) return ex;
        else if(a <= l && r <= b) return dat[now];
        else{
            T vl = query_sub(a, b, 2*now + 1, l, (l + r)/2);
            T vr = query_sub(a, b, 2*now + 2, (l + r)/2, r);
            return calculate(vl, vr);
        }
    }

    inline T operator[](int a) { return query(a, a + 1); }
    void print() {
        for (int i = 0; i < 2 * n - 1; ++i) {
            cout << (*this)[i];
            if (i != n) cout << ",";
        }
        cout << endl;
    }
};

int main()
{
    cin.tie(0); ios::sync_with_stdio(false);
    int i;
    int h,w;
    cin >> h >> w;
    vector<int> v(w, 0);
    const int INF = 1e9;
    set<int> st;
    rep(i,w) st.insert(i);
    RUQ<int> ruq(v);
    rep(i,h){
        int a,b;
        cin >> a >> b;
        --a;    --b;
        auto x = st.lower_bound(a);
        auto y = st.upper_bound(b);
        if(x == y){
            ruq.update(a, b+1, INF);

            int ans = ruq.query(0, w);

            if(ans == INF) cout << -1 << endl;
            else cout << ans + i + 1 << endl;
        }else if(b+1 == w){
            st.erase(x, y);
            ruq.update(a, b+1, INF);

            int ans = ruq.query(0, w);

            if(ans == INF) cout << -1 << endl;
            else cout << ans + i + 1 << endl;
        }else{
            auto it = prev(y);
            int ind = *it;
            st.erase(x, y);
            st.insert(b+1);
            int tmp = ruq.query(ind, ind+1) + (b + 1 - ind);
            ruq.update(b+1, b+2, min(tmp, ruq.query(b+1, b+2)));
            ruq.update(a, b+1, INF);

            int ans = ruq.query(0, w);

            if(ans == INF) cout << -1 << endl;
            else cout << ans + i + 1 << endl;
        }
    }

    return 0;
}

#include <bits/stdc++.h>
#include <string>
#include <vector>
#include <algorithm>
#define rep(i,n) for (int i = 0;i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
int INF = 1e9;
void chmax(int& a, int b) { a = max(a, b);}
void chmin(int& a,int b) {a = min(a,b);}

int main(){
    int h,w;cin >> h >> w;
    map<int,int> mp;
    multiset<int> m;
    rep(i,w) mp[i] = i;
    rep(i,w) m.insert(0);
    rep(i,h){
        int l,r;cin >> l >> r;
        --l;
        map<int,int>::iterator it = mp.lower_bound(l);
        int mr = -1;
        while(it != mp.end() && it->first <= r){
            mr = it->second;
            m.erase(m.find(it->first - it->second));
            mp.erase(it++);
        }
        if(mr != -1 && r < w) {
            mp[r] = mr;
            m.insert(r-mr);
        }
        int  ans = -1;
        if(m.size()>0) {
            ans = *m.begin() + (i+1);
        }
        cout << ans << endl;

    }
}


//#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

#include <atcoder/all>
using namespace atcoder;

#ifdef LOCAL
#include <prettyprint.hpp>
#define debug(...)  cerr << "[" << #__VA_ARGS__ << "]: ", d_err(__VA_ARGS__);
#else
#define debug(...) 83;
#endif

void d_err() {
    cerr << endl;
}

template <typename H, typename... T>
void d_err(H h, T... t) {
    cerr << h << " ";
    d_err(t...);
}

template <typename T>
void print(T x) {
    cout << x << "\n";
}

#define ALL(x) (x).begin(), (x).end()
#define FOR(i, m, n) for (ll i = (m); i < (n); ++i)
#define REVFOR(i, m, n) for (ll i = (n - 1); i >= (m); --i)
#define REP(i, n) FOR(i, 0, n)
#define REVREP(i, n) REVFOR(i, 0, n)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define bcnt __builtin_popcountll

typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<ll,ll> Pll;
typedef pair<int,int> Pin;

ll INF = 1e16;
int inf = 1e9;
ll MOD = 1e9+7;

int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);

    int n, q;
    cin >> n >> q;

    fenwick_tree<ll> ft(n);
    REP(i, n) {
        ll a; cin >> a;
        ft.add(i, a);
    }

    REP(i, q) {
        int t, a, b;
        cin >> t >> a >> b;
        if (t == 0) {
            ft.add(a, b);
        } else {
            print(ft.sum(a, b));
        }
    }

}

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Union{
	vector<int> par;
	vector<int> size;

	Union(int n) : par(n), size(n,1){
	    for(int i=0; i < n; i++){
			size[i] = 1;
			par[i] = i;
		}
	}

	int find(int x){
		if (x == par[x]) return x;
		return par[x] = find(par[x]);
	}

	void unite(int x, int y){
		x = find(x);
		y = find(y);

		if(x == y) return;

		if(size[x] < size[y]) swap(x, y);

		par[y] = x;
		size[x] += size[y];
	}

	bool same(int x, int y){
		return find(x) == find(y);
	}

	int getSize(int x){
		return size[find(x)];
	}
};

struct Edge{
	int a, b, cost;

	bool operator<(const Edge& o) const{
		return cost < o.cost;
	}
};

struct Graph{
	int n;
	vector<Edge> e;

	int kruskal(){
		sort(e.begin(), e.end());

		Union u(n);
		int min_cost = 0;

	    for(int i=0; i<e.size(); i++){
			Edge& x = e[i];
			if (u.same(x.a, x.b) == false){
				min_cost += x.cost;
				u.unite(x.a, x.b);
			}
		}

		return min_cost;
	}
};

int main(){
	Graph g;
	Edge e;
	int m;
	cin >> g.n >> m;

    for(int i=0; i<m; i++){
		cin >> e.a >> e.b >> e.cost;
		g.e.push_back(e);
	}

	cout << g.kruskal() << endl;

	return 0;
}


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

template <typename TYPE>
void print_vec(const vector<TYPE>& v){
	for(int i=0; i<v.size(); i++){
		cout << v[i] << " ";
	}
	cout << endl;
}

template <typename TYPE>
void print_vec2(const vector<vector<TYPE>>& v){
  cout << endl; cout << "       ";
  for(int i=0; i<v[0].size(); i++) cout << i << "   ";
  cout << endl;
	for(int i=0; i<v.size(); i++){
		cout << "i=" << i << ":   ";
		for(int j=0; j<v[i].size(); j++){
			if(v[i][j] == 0) cout << "\x1B[0m" << v[i][j] << "   ";
      else cout << "\x1B[31m" << v[i][j] << "   ";//https://stackoverrun.com/ja/q/12618775
		}
		cout << "\x1B[0m" << endl;
	}
}

int main(){
	int N;
	cin >> N;
	vector<ll> A(N);
	int num_minus = 0;
	for(int i=0; i<N; i++){
		ll a;
		cin >> a;
		if(a<0){
			num_minus++;
			a *= -1;
		}
		A[i] = a;
	}

	sort(A.rbegin(), A.rend());
	ll ans = 0;
	for(int i=0; i<N; i++) ans += A[i];
	if(num_minus % 2 ==1) ans -= 2*A.back();
	cout << ans << endl;

	return 0;
}

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

#define ll long long
#define mtv(kit) cout<<#kit<<" - "<<kit<<"\n";
#define ff first
#define ss second
#define pb push_back
#define rep(i,a,b) for(i=a;i<b;i++)
#define pii pair<ll , ll>
#define all(x) x.begin(),x.end()
#define nl "\n"
#define ump unordered_map

void doit(){
    ll n,i,k,j;
    cin >> n;
    vector< ll >v(n);
    for(i = 0; i < n; i++)cin>>v[i];
    vector<pii>answer(61,{0,0});
    rep(i,0,n){
        rep(j,0,61){
            if(v[i] & (1LL << j) )answer[j].ff++;
            else answer[j].ss++;
        }
    }
    ll ans = 0,mod = 1e9+7;
    rep(i,0,61){
        ll k1 = (answer[i].ff * answer[i].ss)%mod ;
        ll k2 = (1LL << i)%mod;
        k1 = (k1*k2)%mod;
        ans = ((ans % mod) + (k1 % mod)) % mod;
    }
    cout << ans;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t = 1;
    // cin >> t;
    for(ll i = 1; i <= t; i++){
        doit();
    }
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;
using ll = long long;
int INF = 1000000009;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    string s;
    cout << 0 << endl;
    cin >> s;
    if(s == "Vacant"){
        return 0;
    }
    int ok = n;
    int ng = 0;
    string tmp;
    while(tmp!="Vacant")
    {
        int mid = (ok + ng) / 2;
        cout << mid << endl;
        cin >> tmp;
        if(mid%2^tmp==s){
            ng = mid;
        }
        else
        {
            ok = mid;
        }
    }
    return 0;
}

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

int N;
const double EPS = 1e-10;

struct state{
  string name;
  double k;
  state(){}
  state(int P,int A,int B,int C,int D, int E,int F,int S,int M){
    int time = A + B + C + (D + E)*M;
    int num = M * F;
    int mon = num * S;
    int s = mon - P;
    k = (double)s/(double)time;
  }
  bool operator<(const state& st) const {
    return abs(k-st.k) < EPS ? name < st.name : k > st.k;
  }
};

state st[111];
int main(){
  while( cin >> N && N ){
    for(int i=0;i<N;i++){
      string L;int P,A,B,C,D,E,F,S,M;
      cin >> L >> P >> A >> B >> C >> D >> E >> F >> S >> M;
      st[i] = state(P,A,B,C,D,E,F,S,M);
      st[i].name = L;

    }
    sort(st,st+N);
    for(int i=0;i<N;i++)
      cout << st[i].name << endl;
    cout << "#" << endl;
  }
}


#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<cmath>
#include<climits>
#include<ctime>
#include<cstring>
#include<iomanip>

#define ALL(v) (v).begin(),(v).end()
#define REP(i,p,n) for(int i=p;i<(int)(n);++i)
#define rep(i,n) REP(i,0,n)
#define dump(a) (cerr << #a << "=" << (a) << endl)
#define DUMP(list) cout << "{"; for(auto nth : list){ cout << nth << " ";}cout << "}" << endl;

using namespace std;

string table[]={"qwertasdfgzxcvb","yuiophjklnm"};

int main(){

	while(true){
		int n,q;
		vector<int> date;

		cin >> n >> q;

		if(n==0&&q==0) break;

		for(int i=0;i<=100;i++){
			date.push_back(0);
		}

		for(int i=0;i<n;i++){
			int m,d;
			cin >> m;
			for(int k=0;k<m;k++){
				cin >> d;
				date[d]++;
			}
		}

		int decide=0,day=0;

		for(int i=0;i<100;i++){
			if(date[i]>decide && date[i] >= q){
				decide=date[i];
				day=i;
			}
		}

		cout << day << endl;
	}

}

#include <iostream>
#include <map>

using namespace std;

#define MN 101

int n;
int ks[MN];
string raw;

map<char, int> kmap;
map<int, char> rkmap;

void init_() {
    for (char i = 'a'; i <= 'z'; i++) {
        kmap[i] = i - 'a';
        rkmap[i - 'a'] = i;
    }
    for (char i = 'A'; i <= 'Z'; i++) {
        kmap[i] = i - 'A' + 26;
        rkmap[i - 'A' + 26] = i;
    }
}

bool init() {
    cin >> n;
    if (n == 0) return false;
    for (int i = 0; i < n; i++) {
        cin >> ks[i];
    }
    cin >> raw;
    return true;
}

char before(char r, int b) {
    int i = kmap[r];
    return rkmap[(i + 52 - b) % 52];
}

void solve() {
    string ans = raw;
    int kindex = 0;
    for (int i = 0; i < raw.size(); i++) {
        ans[i] = before(raw[i], ks[kindex]);
        kindex = (kindex + 1 + n) % n;
    }
    cout << ans << endl;
}

int main() {
    init_();
    while (init()) {
        solve();
    }
    return 0;
}


#include "bits/stdc++.h"

#define REP(i,num) for(int i=0;i<(num);++i)
#define LOOP(i) while(i--)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto& x:c){cout<<x<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=int>
T in(){T x; cin >> x; return (x);}
template<typename T=int,typename C=vector<T>>
C vecin(int N){C x(N);REP(i,N){x[i]=in<T>();}return move(x);}

void vout(){cout << endl;}
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){cout << ' ' << h;vout(forward<Tail>(t)...);}
void out(){cout << endl;}
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){cout << h;vout(forward<Tail>(t)...);}

class Data{
public:
	ll first,second,third;
	Data()=default;
	Data(ll f,ll s,ll t):first(f),second(s),third(t){}
};

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	ll N=in(),K=in();
	out(N-K+1);

	return 0;
}

#include<iostream>
#include<iomanip>
#include<string>
#include<algorithm>
#include<vector>
#include<utility>
#include<tuple>
#include<map>
#include<queue>
#include<stack>
#include<deque>
#include<bitset>
#include<math.h>
using namespace std;
int main(){
    int n,m;
    cin >> n >> m;
    vector<int> num(n,0);
    for(int i=0;i<m;i++){
        int s,c;
        cin >> s >> c;
        if(num.size()>=2 && s==1 && c==0){
            cout << -1 << endl;
            return 0;
        }
        if(num.at(s-1)==0 || num.at(s-1)==c){
            num.at(s-1)=c;
        }else{
            cout << -1 << endl;
            return 0;
        }
    }

    if(num.at(0)==0 && num.size()>=2) num.at(0)=1;
    for(int i=0;i<n;i++) cout << num.at(i);
    cout << endl;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
#include <functional>
#include <ctime>
#include <fstream>
#include <cmath>
#include <limits>
#include <chrono>
#include <numeric>
#include <type_traits>
#include <iomanip>
#include <float.h>
#include <math.h>
#include <cassert>
#pragma warning (disable: 4996)
using namespace std;

using ll = long long;
unsigned euclidean_gcd(unsigned a, unsigned b) {
    if (a < b) return euclidean_gcd(b, a);
    unsigned r;
    while ((r = a % b)) {
        a = b;
        b = r;
    }
    return b;
}

ll ll_gcd(ll a, ll b) {
    if (a < b) return ll_gcd(b, a);
    ll r;
    while ((r = a % b)) {
        a = b;
        b = r;
    }
    return b;
}

struct UnionFind {
    vector <ll> par;
    vector <ll> siz;
    UnionFind(ll sz_) : par(sz_), siz(sz_, 1LL) {
        for (ll i = 0; i < sz_; ++i) par[i] = i;
    }
    void init(ll sz_) {
        par.resize(sz_);
        siz.assign(sz_, 1LL);
        for (ll i = 0; i < sz_; ++i) par[i] = i;
    }
    ll root(ll x) {
        while (par[x] != x) {
            x = par[x] = par[par[x]];
        }
        return x;
    }
    bool merge(ll x, ll y) {
        x = root(x);
        y = root(y);
        if (x == y) return false;
        if (siz[x] < siz[y]) swap(x, y);
        siz[x] += siz[y];
        par[y] = x;
        return true;
    }

    bool issame(ll x, ll y) {
        return root(x) == root(y);
    }

    ll size(ll x) {
        return siz[root(x)];
    }
};

long long modpow(long long a, long long n, long long mod) {
    if (n < 0)return 0;
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

long long modinv(long long a, long long mod) {
    return modpow(a, mod - 2, mod);
}

ll merge_cnt(vector<ll>& a) {
    int n = a.size();
    if (n <= 1) { return 0; }

    ll cnt = 0;
    vector<ll> b(a.begin(), a.begin() + n / 2);
    vector<ll> c(a.begin() + n / 2, a.end());

    cnt += merge_cnt(b);
    cnt += merge_cnt(c);

    int ai = 0, bi = 0, ci = 0;
    while (ai < n) {
        if (bi < b.size() && (ci == c.size() || b[bi] <= c[ci])) {
            a[ai++] = b[bi++];
        }
        else {
            cnt += n / 2 - bi;
            a[ai++] = c[ci++];
        }
    }
    return cnt;
}

int main() {
    ll n;
    cin >> n;
    cout << 0 << endl;
    string s;
    cin >> s;
    if (s == "Vacant")return 0;
    else {
        ll ok = 0;
        ll ng = n;
        while (true) {
            ll mid = (ok + ng) / 2;
            cout << mid << endl;
            string t;
            cin >> t;
            if (t == "Vacant")return 0;
            if (!((t == s) ^ (ok % 2 == mid % 2))) {
                ok = mid;
                s = t;
            }
            else ng = mid;
        }
    }
}

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

#define d(x) cerr << #x ":" << x << endl;
#define dd(x, y) cerr << "(" #x "," #y "):(" << x << "," << y << ")" << endl
#define rep(i, n) for (int i = (int)(0); i < (int)(n); i++)
#define repp(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define all(v) v.begin(), v.end()
#define dump(v)                  \
    cerr << #v ":[ ";            \
    for (auto macro_vi : v) {    \
        cerr << macro_vi << " "; \
    }                            \
    cerr << "]" << endl;
#define ddump(v)                           \
    cerr << #v ":" << endl;                \
    for (auto macro_row : v) {             \
        cerr << "[";                       \
        for (auto macro__vi : macro_row) { \
            cerr << macro__vi << " ";      \
        }                                  \
        cerr << "]" << endl;               \
    }
using lint       = long long;
const int INF    = 1e9;
const lint LINF  = 1e18;
const lint MOD   = 1e9 + 7;
const double EPS = 1e-10;

int query(int u) {
    cout << u << endl;
    fflush(stdout);

    string x;
    cin >> x;

    if (x == "Vacant") {
        return 0;
    } else if (x == "Male") {
        return 1;
    } else
        return -1;
}

int main() {
    int N;
    cin >> N;
    int basic = query(0);

    if (basic == 0) return 0;

    int low = 0, high = N;

    while (true) {
        int mid = (low + high) >> 1;
        int col = query(mid);

        if (col == 0) return 0;

        int exp = (mid % 2 == 1 ? -basic : basic);

        if (exp == col) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
}


#include <bits/stdc++.h>
#define ll long long
#define rep(i,n) for(int i=0;i<n;i++)
#define rrep(i,n) for(int i=1;i<=n;i++)
#define drep(i,n) for(int i=n;i>=0;i--)
#define INF 100000005
#define MAX 100000001
#define dmp make_pair
#define dpb push_back
#define fi first
#define se second
using namespace std;
//__gcd(a,b), __builtin_popcount(a);

int n, m, a[10], ans;
map<int,int> mp;

int solve(int tmp[4], int k, int sum, int p){
	int t, u[4];
	rep(i,4)u[i] = tmp[i];
	u[k++] = p;
	if(a[p] >= 10)sum = sum*100+a[p];
	else sum = sum*10+a[p];

	if(m == k){
		if(mp[sum]==0)ans++;
		mp[sum] = 1;
		return 0;
	}

	for(int i = 0;i < n;i++){
		t = 1;
		rep(j,k)if(u[j] == i)t = 0;
		if(t)solve(u, k, sum, i);
	}
	return 0;
}

int main(){
	int u[4] = {0,0,0,0};
	while(1){
		ans = 0;
		mp.clear();
		scanf("%d%d", &n, &m);
		if(!n)break;
		rep(i,n)scanf("%d", &a[i]);
		for(int i = 0;i < n;i++){
			solve(u, 0, 0, i);
		}
		printf("%d\n", ans);
	}
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,k;
int ans;
vector<int>v;
vector<int>pos;
int sol(int i,int j){
	int smsm=0;
	int tmp=k;
	priority_queue<int>pq;
	for(int s=0;s<=i&&tmp;s++){
		smsm+=v[s];
		pq.push(-v[s]);
		tmp--;if(tmp==0)break;
	}
	if(j<=i){
		int ssss=smsm;
		int ttmp=tmp;
		priority_queue<int>ppq=pq;
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;if(ttmp==0)break;
		}
		ans=max(ans,ssss);
	}else{
		priority_queue<int>ppq=pq;
		int ttmp=tmp;
		int ssss=smsm;
		for(int z=i+1;z<=j&&ttmp;z++){
			ppq.push(-v[z]);
			ssss+=v[z];
			ttmp--;
			if(ttmp==0)break;
		}
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;
			if(ttmp==0)break;
		}
		ans=max(ans,ssss);
		ppq=pq;ttmp=tmp;ssss=smsm;
		for(int z=n-1;z>=j&&ttmp;z--){
			ppq.push(-v[z]);
			ssss+=v[z];
			ttmp--;if(ttmp==0)break;
		}
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;if(ttmp==0)break;
		}
		ans=max(ans,ssss);
	}
	priority_queue<int>cls;
	smsm=0;tmp=k;pq=cls;
	for(int z=n-1;z>=i&&tmp;z--){
		smsm+=v[z];
		pq.push(-v[z]);
		tmp--;if(tmp==0)break;
	}
	if(j>=i){
		int ssss=smsm;
		int ttmp=tmp;
		priority_queue<int>ppq=pq;
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;if(ttmp==0)break;
		}
		ans=max(ans,ssss);
	}else{
		priority_queue<int>ppq=pq;
		int ttmp=tmp;
		int ssss=smsm;
		for(int z=i-1;z>=j&&ttmp;z--){
			ppq.push(-v[z]);
			ssss+=v[z];
			ttmp--;if(ttmp==0)break;
		}
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;if(ttmp==0)break;
		}
		ans=max(ans,ssss);
		ppq=pq;ttmp=tmp;ssss=smsm;
		for(int z=0;z<=j&&ttmp;z++){
			ppq.push(-v[z]);
			ssss+=v[z];
			ttmp--;if(ttmp==0)break;
		}
		while(ppq.size()&&ttmp){
			if(ppq.top()<=0)break;
			ssss+=ppq.top();ppq.pop();
			ttmp--;if(ttmp==0)break;
		}
		ans=max(ans,ssss);
	}
}

int main(){
	ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
	cin>>n>>k;
	for(int i=0;i<n;i++){
		int a;cin>>a;
		v.push_back(a);
		if(a>0)pos.push_back(i);
	}
	for(int i=0;i<pos.size();i++){
		for(int j=0;j<pos.size();j++){
			sol(pos[i],pos[j]);
			// cout<<"---------------"<<endl;
			// cout<<pos[i]<<' '<<pos[j]<<endl;
			// cout<<ans<<endl;
		}
	}
	cout<<ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int n,m,a[N],ans,v,p;
LL sum[N];
bool ck(int x){
	if(n-x+1<=p)return true;
	if(x+p-1>=v){
		int pos=a[n-p+1];
		return (a[x]+m>=pos);
	}
	int lft=v-(x+p-1);
	LL mid=0,num=0;
	for(int i=x+1;i<=n-p+1;i++){
		if(a[i]>a[x]+m)return false;
		mid+=a[i];num++;
	}
	mid+=1ll*m*lft;
	LL tmp=(mid+num-1)/num;
	//cout<<x<<" "<<lft<<" "<<a[x]+m<<" "<<tmp<<endl;
	return a[x]+m>=tmp;
}
int main(){
	scanf("%d%d%d%d",&n,&m,&v,&p);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++)sum[i]=sum[i-1]+a[i];
	int L=1,R=n;
	while(L<=R){
		int mid=(L+R)>>1;
		if(ck(mid))ans=mid,R=mid-1;
		else L=mid+1;
	}
	printf("%d\n",(n-ans+1));
}

#include <bits/stdc++.h>
typedef long long int LL;
typedef unsigned long long int ULL;
using namespace std;

// 插入此處

LL a[100005];

int main() {
    LL n, m, v, p;
    cin >> n >> m >> v >> p;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    sort(a, a + n, [](LL x, LL y) { return x > y; });
    // for (int i = 0; i < n; i++) {
    //     printf("%lld ", a[i]);
    // }
    // puts("");
    LL ans;
    LL agg = 0;
    for (ans = p; ans < n; ans++) {
        // 前後都還夠塞
        LL les = n - ans;
        LL re = v - (p - 1) - les;
        agg += a[ans - 1];
        if (re <= 0) {
            if (a[p - 1] <= a[ans] + m) {
                continue;
            } else {
                break;
            }
        } else {
            // 要開始塞中間了
            LL space = (ans - p + 1) * (a[ans] + m) - agg;
            LL vote = re * m;
            // printf("ans = %lld, re = %lld, space = %lld, vote = %lld\n", ans, re, space, vote);
            if (a[p - 1] <= a[ans] + m && space >= vote) {
                continue;
            } else {
                break;
            }
        }
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>
#define rep(i,l,n) for(int i=l;i<n;i++)
#define all(a) a.begin(),a.end()
#define o(a) cout<<a<<endl
using namespace std;

int main(){
	int n,q;
	while(1){
		pair<int,int> data[101]={};
		rep(i,0,101){
			data[i].second=-i;
		}
		cin>>n>>q;
		if(n==0 && q==0) break;
		rep(i,0,n){
			int m,d;
			cin>>m;
			rep(j,0,m){
				cin>>d;
				data[d].first++;
			}
		}
		sort(data,data+101);
		reverse(data,data+101);
		if(data[0].first<q) cout<<0<<endl;
		else cout<<-data[0].second<<endl;
	}
}

/*for(map<int,int>::iterator it=dat.begin();it!=dat.end();it++)
	if(it->second>Max){
		max=it->second;
		ans=it->first;
	}*/

#include <bits/stdc++.h>
using namespace std;
template <class T> inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T> inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return 1;
    }
    return 0;
}

#ifdef DEBUG
void debug() { cerr << "\n"; }
template <class T> void debug(const T &x) { cerr << x << "\n"; }
template <class T, class... Args> void debug(const T &x, const Args &... args) {
    cerr << x << " ";
    debug(args...);
}
template <class T> void debugVector(const vector<T> &v) {
    for(const T &x : v) {
        cerr << x << " ";
    }
    cerr << "\n";
}
#else
template <class T, class... Args>
void debug(const T &x, const Args &... args) {}
template <class T> void debugVector(const vector<T> &v) {}
#endif

using ll = long long;
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
const double EPS = 1e-7;
const int INF = 1 << 30;
const ll LLINF = 1LL << 60;
constexpr int MOD = 1000000007;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

//-------------------------------------

void solve() {
    int N;
    cin >> N;
    vector<ll> a(N);
    for(int i = 0; i < N; i++) {
        cin >> a[i];
    }
    string s;
    cin >> s;
    reverse(ALL(a));
    reverse(ALL(s));
    vector<ll> base;
    for(int i = 0; i < N; i++) {
        ll v = a[i];
        sort(RALL(base));
        for(ll e : base) {
            chmin(v, v ^ e);
        }
        if(v) {
            if(s[i] == '0') {
                base.emplace_back(v);
            } else {
                cout << 1 << "\n";
                return;
            }
        }
    }
    cout << 0 << "\n";
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    for(int i = 0; i < t; i++) {
        solve();
    }
}


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

#define pb push_back

void solve(){
 ll sx,sy,tx,ty;
 cin>>sx>>sy>>tx>>ty;

 ll dx=tx-sx;
 ll dy=ty-sy;
 string s1,s2;
 for(int i=0;i<dy;i++){
    s1+='U';
    s2+='D';
 }
 for(int i=0;i<dx;i++)
{
  s1+='R';
  s2+='L';
}
string f1= "LU"+s1+"RD";
string f2="RD"+s2+"LU";
cout<<s1+s2+f1+f2<<endl;
}

int main() {
   #ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  freopen("output.txt","w",stdout);
  #endif

 ios_base::sync_with_stdio(0);
 cin.tie(0);

int t=1 ;  while(t--)
 solve();

return 0;
}

#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <ctype.h>
#include <algorithm>
#include <cmath>

#define REP(i, n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()
#define square(x) (x) * (x)
#define cube(x) (x) * (x) * (x)

const int INF = 1e9;

using namespace std;

class dice{
    private:
    int s[6];
    int top;
    int bottom;
    int r_side;
    int l_side;
    int face;
    int rev;

    public:
    dice(){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        s[0] = 1;
        s[1] = 2;
        s[2] = 3;
        s[3] = 4;
        s[4] = 5;
        s[5] = 6;
    }

    dice(int a[5]){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        REP(i, 6) s[i] = a[i];
    }

    dice(int x, int y, int z, int u, int v, int w){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        s[0] = x;
        s[1] = y;
        s[2] = z;
        s[3] = u;
        s[4] = v;
        s[5] = w;
    }

    int get_top() {
        return s[top];
    }

    int get_bottom(){
        return s[bottom];
    }

    int get_r_side(){
        return s[r_side];
    }

    int get_l_side(){
        return s[l_side];
    }

    int get_face(){
        return s[face];
    }

    int get_rev(){
        return s[rev];
    }

    int set_top(int i) {
        top = i;
        bottom = 5 - top;
        r_side = (i+1)%5;
        l_side = 5 - r_side;
        face = (i+2)%5;
        rev = 5 - face;
        return s[top];
    }

    int rotate_r(int i) {
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = face;
            face = r_side;
            r_side = rev;
            rev = l_side;
            l_side = temp;
        }
        return s[top];
    }

    int roll_r(int i) {
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = top;
            top = l_side;
            l_side = bottom;
            bottom = r_side;
            r_side = temp;
        }
        return s[top];
    }

    int roll_f(int i){
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = top;
            top = face;
            face = bottom;
            bottom = rev;
            rev = temp;
        }
        return s[top];
    }

};

int main() {
    int in[6];
    REP(i, 6) cin >> in[i];
    dice d = dice(in);
    string roll;
    cin >> roll;
    while(roll.size() != 0){
        string order = roll.substr(0, 1);
        if(order == "E")
            d.roll_r(1);
        else if(order == "S")
            d.roll_f(-1);
        else if(order == "N")
            d.roll_f(1);
        else if(order == "W")
            d.roll_r(-1);
        roll = roll.substr(1);
    }
    cout << d.get_top() << endl;
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define int long long
using namespace std;
inline int read(){
	int f=1,ans=0;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){ans=ans*10+c-'0';c=getchar();}
	return f*ans;
}
const int MAXN=100001;
int m,k,ans,n,x[MAXN],d[MAXN],a[MAXN],fa[MAXN][61],p[MAXN];
signed main(){
//	freopen("2.in","r",stdin);
	n=read();
	for(int i=1;i<=n;i++) x[i]=read(),d[i]=i,p[i]=x[i]-x[i-1];
	m=read(),k=read();
	for(int i=1;i<=m;i++) a[i]=read(),swap(d[a[i]],d[a[i]+1]);
	for(int i=1;i<=n;i++) fa[i][0]=d[i];
	for(int j=1;j<=60;j++)
		for(int i=1;i<=n;i++) fa[i][j]=fa[fa[i][j-1]][j-1];
	for(int i=1;i<=n;i++){
		int res=i;
		int K=k;
		for(int j=60;j>=0;j--) if(K-(1ll<<j)>=0) K-=(1ll<<j),res=fa[res][j];
		ans+=p[res];
		printf("%lld.0\n",ans);
	}return 0;
}/*
3
1 -1 1
2 2
2 2
*/

#include <iostream>
#include <vector>
using namespace std;

int main() {
	int n;

	while (cin >> n) {
		if (n == 0) break;
		vector<int> array(n);
		for (int i = 0; i < n; i++) {
			cin >> array.at(i);
		}

		long max = array.at(0);
		for (int j = 0; j < n; j++) {
			long total = 0;
			for (int k = 0; k < n - j; k++) {
				total += array.at(j + k);
				if (total > max) max = total;
			}
		}

		cout << max << endl;
	}
	return 0;
}


#include <stdio.h>
#include <limits.h>
#include <math.h>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>

#define VARIABLE(x) cerr << #x << "=" << x << endl
#define BINARY(x) static_cast<bitset<16> >(x);
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define if_range(x, y, w, h) if (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))

const int INF = 1000000000;
typedef double D;
const double EPS = 1e-8;
const double PI = 3.14159;
int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1};
using namespace std;
//typedef pair<int, int> P;

/** Problem0546 : Lining up the cards **/

vector<string> card;
bool used[10];
set<string> ans;
int N, K;

void solve(int n, string s)
{
	if (n==K) ans.insert(s);
	else {
		rep(i, N) {
			if (!used[i]) {
				used[i] = true;
				solve(n+1, s+card[i]);
				used[i] = false;
			}
		}
	}
}

int main()
{
	while (cin>>N, N) {
		ans.clear();
		card.clear();
		fill(used, used+10, false);

		cin>>K;
		rep(i, N) {
			string s; cin>>s;
			card.push_back(s);
		}
		solve(0, "");
		cout << ans.size() << endl;
	}
}

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
	int n, k;
	while(cin >> n >> k && (n || k)){
		int card[10] = {0};
		map<string, int> m;
		for(int i = 0; i < n; ++i)
			cin >> card[i];

		int ans = 0;
		if(k == 2){
			for(int i = 0; i < n; ++i){
				for(int j  = 0; j < n; ++j){
					if(i == j)
						continue;
					string str = to_string(card[i]) + to_string(card[j]);
					if(m[str] == 0){
						ans++;
						m[str] = 1;
					}
				}
			}
		}
		else if(k == 3){
			for(int i = 0; i < n; ++i){
				for(int j  = 0; j < n; ++j){
					if(i == j)
						continue;
					for(int k = 0; k < n; ++k){
						if(i == k || j == k)
							continue;
						string str = to_string(card[i]) + to_string(card[j]) + to_string(card[k]);
						if(m[str] == 0){
							ans++;
							m[str] = 1;
						}
					}
				}
			}
		}
		else if(k == 4){
			for(int i = 0; i < n; ++i){
				for(int j  = 0; j < n; ++j){
					if(i == j)
						continue;
					for(int k = 0; k < n; ++k){
						if(i == k || j == k)
							continue;
						for(int l = 0; l < n; ++l){
							if(i == l || j ==l ||  k == l)
								continue;
							string str = to_string(card[i]) + to_string(card[j]) + to_string(card[k]) + to_string(card[l]);
				 			if(m[str] == 0){
								ans++;
								m[str] = 1;
							}
						}
					}
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using ll = long long;
ll GetDigit(ll num){ return log10(num)+1; } //numの桁数を求める

int main()
{
    int a,b,c,d;
    cin >> a >> b >> c >> d;
    a = min(a,b);
    c = min(c,d);
    int ans = a+c;
    cout << ans << endl;
    return 0;
}

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

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
    bool first = true;
    string res = "{";
    for (int i = 0; i < static_cast<int>(v.size()); i++) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template <size_t N>
string to_string(bitset<N> v) {
    string res = "";
    for (size_t i = 0; i < N; i++) {
        res += static_cast<char>('0' + v[i]);
    }
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

#ifndef ONLINE_JUDGE
#define debug(...) cerr<<"LINE ("<< __LINE__ << ") : [" << #__VA_ARGS__ << "] -> ", debug_out(__VA_ARGS__)
#else
#define debug(...)
#endif

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    vector<int> a = {111, 222, 333, 444, 555, 666, 777, 888, 999};
    int n;
    cin >> n;
    auto it = lower_bound(a.begin(), a.end(), n);
    cout << *it;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rrep(i, n) for(int i = n-1; i >= 0; i--)
#define  all(x) (x).begin(),(x).end()     // 昇順ソート
#define  rall(v) (v).rbegin(), (v).rend() // 降順ソート
#define  FastIO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
typedef long long ll;
using P = pair<int,int>;
using VI = vector<int>;
using VVI = vector<vector<int>>;
using VL = vector<ll>;
using VVL = vector<vector<ll>>;
using VP = vector<P>;
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return true; } return false; }

const ll INF = 1LL<<60;

int main(){
    int d;
    ll g;
    cin >> d >> g;
    VP q(d);
    rep(i,d) cin >> q[i].first >> q[i].second;

    VI p(d);
    rep(i,d) p[i] = i;

    ll ans = INF;
    do{
        VI pp(d);
        rep(i,d) pp[p[i]] = i;

        ll gg = g;
        ll cnt = 0;
        rep(i,d){
            int j = pp[i];
            ll pc = (j + 1) * 100;
            ll num = min((ll)q[j].first, ((gg + (pc-1)) / pc));
            cnt += num;

            gg -= pc * num;
            gg -= q[j].second;

            if (gg <= 0) break;
        }

        ans = min(ans, cnt);

    } while(next_permutation(all(p)));

    cout << ans << endl;
    return 0;
}

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

typedef long long ll;

#define REP(i, n) for(ll i = 0; i < n; i++)
#define REPR(i, n) for(ll i = n; i >= 0; i--)
#define FOR(i, m, n) for(ll i = m; i < n; i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define INF 1e9
#define LINF 1e18

int main() {
    int D,G; cin >> D >> G;
    vector<pair<ll,ll>> score(D+1);
    REP(i,D){
        int p,c; cin >> p >> c;
        score[i] = {p,c};
    }

    int ans = INF;
    REP(bit, 1<<D){
        vector<int> S(D,0);
        int sum = 0;
        int cnt = 0;

        REP(i,D){
            if(bit & (1<<i)){
                S[i] = 1;
                sum += score[i].first*(i+1)*100 + score[i].second;
                cnt += score[i].first;
            }
        }

        if(G<=sum){
            ans = min(ans, cnt);
            continue;
        }

        REPR(i,D-1){
            if(S[i]==1) continue;
            REP(j,score[i].first){
                sum += 100*(i+1);
                cnt++;

                if(G<=sum){
                    ans = min(ans, cnt);
                    continue;
                }
            }
        }
        ans = min(ans, cnt);
    }
    cout << ans << endl;

    return 0;
}


#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <memory>
#include <iomanip>

std::vector<int> parse_line(std::string const& line) {
    using namespace std;
    vector<int> result;
    istringstream s(line);
    string element;
    while (getline(s, element, ' ')) {
        stringstream buf;
        int value = 0;
        buf << element;
        buf >> value;
        result.push_back(value);
    }
    return std::move(result);
}
int main(int argc, char* argv[])
{
    using namespace std;
    while (true) {
        string line;
        getline(std::cin, line);
        auto elements = parse_line(line);
        auto length = elements[0];
        if (length == 0) break;
        vector<int> total(length + 1);
        size_t width = length + 1;
        for (size_t i = 0; i < length; ++i) {
            getline(cin, line);
            elements = parse_line(line);
            int sum = 0;
            for (size_t n = 0; n < length; ++n) {
                int val = elements[n];
                sum += val;
                total[n] += val;
                cout << setw(5) << val;
            }
            cout << setw(5) << sum << endl;
            total[length] += sum;
        }
        for (size_t i = 0; i < width; ++i) {
            cout << setw(5) << total[i];
        }
        cout << endl;
    }

    return 0;
}

#include <algorithm>
#include <cmath>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <cassert>
#include <functional>

using namespace std;

#define LOG(...) printf(__VA_ARGS__)
//#define LOG(...)
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define REP(i,n) for(int i=0;i<(int)(n);++i)
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
#define RSORT(c) sort((c).rbegin(),(c).rend())
#define CLR(a) memset((a), 0 ,sizeof(a))

typedef long long ll;
typedef unsigned long long ull;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vb> vvb;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int dx[] = { -1, 0, 1, 0 }; const int dy[] = { 0, 1, 0, -1 };

int main() {
	int n;
	while (cin >> n, n){
		vector<vector<int>> hyou(n + 1, vector<int>(n + 1, 0));
		REP(i, n){
			REP(j, n){
				int num;
				cin >> num;
				hyou[i][j] = num;
			}
		}
		REP(i, n){
			REP(j, n){
				hyou[i][n] += hyou[i][j];
			}
		}
		REP(j, n){
			REP(i, n){
				hyou[n][j] += hyou[i][j];
			}
		}
		REP(i, n){
			hyou[n][n] += hyou[i][n];
		}
		REP(i, n + 1){
			REP(j, n + 1){
				printf("%5d", hyou[i][j]);
			}
			printf("\n");
		}
	}
}


#include <bits/stdc++.h>
#include <iomanip>
using namespace std;
#define reps(i,s,n) for(int i = s; i < n; i++)
#define rep(i,n) reps(i,0,n)
#define Rreps(i,n,e) for(int i = n - 1; i >= e; --i)
#define Rrep(i,n) Rreps(i,n,0)
#define ALL(a) a.begin(), a.end()
#define fi first
#define se second
#define mp make_pair
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

ll N,M,H,W,K,Q,A,B;
string S;
//const ll MOD = 998244353;
const ll MOD = (1e+9) + 7;
const ll INF = 1LL << 60;
typedef pair<ll,ll> P;

int main(){
    cin>>N>>M>>Q;
    vector<string> grid(N);
    rep(i,N) cin>>grid[i];
    mat edge(N, vec(M, 0)), num(N + 1, vec(M + 1, 0)), addr(N, vec(M,0)), addc(N, vec(M,0));
    rep(i,N){
        rep(j,M){
            bool blue = grid[i][j] == '1';
            if(i > 0) {
                edge[i][j] += edge[i-1][j] + (blue && grid[i-1][j] == '1');
                addc[i][j] = addc[i-1][j] + (blue && grid[i-1][j] == '1');
            }
            if(j > 0) {
                edge[i][j] += edge[i][j-1] + (blue && grid[i][j-1] == '1');
                addr[i][j] = addr[i][j-1] + (blue && grid[i][j-1] == '1');
            }
            if(i > 0 && j > 0) edge[i][j] -= edge[i-1][j-1];
            num[i+1][j+1] = num[i][j+1] + num[i+1][j] - num[i][j] + blue;
        }
    }
    vec x(2), y(2);
    rep(i,Q){
        rep(j,2) cin>>x[j]>>y[j];
        --x[0], --y[0];
        ll res = 0;
        rep(j,2) rep(k,2) res += (j^k ? -1 : 1) * num[x[j]][y[k]];
        --x[1], --y[1];
        rep(j,2) rep(k,2) res += (j^k ? 1 : -1) * edge[x[j]][y[k]];
        res -= addr[x[0]][y[1]] - addr[x[0]][y[0]];
        res -= addc[x[1]][y[0]] - addc[x[0]][y[0]];
        cout<<res<<endl;
    }
    /*rep(i,N){
        rep(j,M) cout<<edge[i][j]<<' ';
        cout<<endl;
    }*/
}

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <map>
#include <deque>
#include <string.h>
using namespace std;

#define REP(i,n) for(int i = 0; i < n; i++)
#define ALL(v) v.begin(),v.end()
typedef long long ll;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef pair<string,string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pi> vpi;
typedef vector<ll> vll;
typedef vector<vll> vvll;

double EPS = 1e-9;
int INFi = 1000000005;
long long INFll = 1000000000000000005ll;
double PI = acos(-1);
int dirx[8] = {-1,0,0,1,-1,-1,1,1};
int diry[8] = {0,1,-1,0,-1,1,-1,1};
ll MOD = 1000000007;

int N, M, Q;
const int MAX_NM = 2000;
const int MAX_Q = 200000;
string S[MAX_NM];
int X1[MAX_Q], Y1[MAX_Q], X2[MAX_Q], Y2[MAX_Q];

int main(){
  cin >> N >> M >> Q;
  REP(i, N) cin >> S[i];
  REP(i, Q) cin >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];
  REP(i, Q) {
    X1[i]--;
    Y1[i]--;
    X2[i]--;
    Y2[i]--;
  }

  int blue[N][M], vert[N][M], hori[N][M];
  REP(i, N) REP(j, M) {
    blue[i][j] = 0;
    vert[i][j] = 0;
    hori[i][j] = 0;
  }

  REP(i, N) {
    REP(j, M) {
      if(i > 0) {
        blue[i][j] += blue[i - 1][j];
        vert[i][j] += vert[i - 1][j];
        hori[i][j] += hori[i - 1][j];
      }
      if(j > 0) {
        blue[i][j] += blue[i][j - 1];
        vert[i][j] += vert[i][j - 1];
        hori[i][j] += hori[i][j - 1];
      }
      if(i > 0 && j > 0) {
        blue[i][j] -= blue[i - 1][j - 1];
        vert[i][j] -= vert[i - 1][j - 1];
        hori[i][j] -= hori[i - 1][j - 1];
      }
      if(S[i][j] == '1') {
        blue[i][j]++;
        if(i > 0 && S[i - 1][j] == '1') vert[i][j]++;
        if(j > 0 && S[i][j - 1] == '1') hori[i][j]++;
      }
    }
  }

  REP(i, Q) {
    ll ans = 0;
    ll b = 0, v = 0, h = 0;
    b += blue[X2[i]][Y2[i]];
    v += vert[X2[i]][Y2[i]];
    h += hori[X2[i]][Y2[i]];
    if(X1[i] > 0) {
      b -= blue[X1[i] - 1][Y2[i]];
      v -= vert[X1[i]][Y2[i]];
      h -= hori[X1[i] - 1][Y2[i]];
    }
    if(Y1[i] > 0) {
      b -= blue[X2[i]][Y1[i] - 1];
      v -= vert[X2[i]][Y1[i] - 1];
      h -= hori[X2[i]][Y1[i]];
    }
    if(X1[i] > 0 && Y1[i] > 0) {
      b += blue[X1[i] - 1][Y1[i] - 1];
      v += vert[X1[i]][Y1[i] - 1];
      h += hori[X1[i] - 1][Y1[i]];
    }
    cout << b - v - h << endl;
  }

  return 0;
}


#define _USE_MATH_DEFINES
#include <iostream>
#include <string>
#include <utility>
#include <stack>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
#include <climits>
#include <set>
#include <cmath>
#include <numeric>
#include <iomanip>

using namespace std;
const long long MOD = 1000000007;
int main(){
    int N;
    string S;
    cin >> N;
    cin >> S;

    int current_open = 0;
    long long N_fact = 1;
    for(int i = 1; i <= N; i++){
        N_fact = (N_fact * i) % MOD;
    }

    long long ans = 1;
    for(int i = 0; i < S.size(); i++){
        if(S[i] == 'B'){
            if(current_open % 2 == 0){
                current_open ++;
            } else {
                ans = (ans * current_open) % MOD;
                current_open --;
            }
        } else {
            if(current_open % 2 == 0){
                if(current_open <= 0){
                    ans = 0;
                    break;
                } else {
                    ans = (ans * current_open) % MOD;
                    current_open --;
                }
            } else {
                current_open ++;
            }
        }
    }

    ans = (ans * N_fact) % MOD;

    if(current_open != 0){
        cout << 0 << endl;
    } else {
        cout << ans << endl;
    }
}

#include<iostream>
#include<cstdio>
const int N=2e5+5;
char s[N];
typedef long long ll;
const ll mod=1e9+7;
int d[N];
int main() {
    int n;
    scanf("%d",&n);
    scanf("%s",s+1);
    if(s[1]=='W') return !printf("0");
    d[1]=0;
    for(int i=2;i<=n+n;i++) {
        if(s[i]==s[i-1]) d[i]=d[i-1]^1;
        else d[i]=d[i-1];
    }
    int num[2]={0,0};
    for(int i=1;i<=n+n;i++) num[d[i]]++;
    if(num[0]!=n) return !printf("0");
    ll ans=1;
    int cnt=0;
    for(int i=1;i<=n+n;i++) {
        if(d[i]) ans=ans*cnt%mod,cnt--;
        else cnt++;
        if(cnt<0) return !printf("0");
    }
    for(int i=1;i<=n;i++) ans=ans*i%mod;
    printf("%lld\n",ans);
    return 0;
}


#include<iostream>
#include<string>
using namespace std;

#define W 12
#define H 12

int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
string mass[W];

void rec(int x, int y)
{
	int xx, yy;
	int i;
	mass[x][y] = '2';
	for (i = 0; i < 4; i++) {
		yy = y+dy[i];
		xx = x+dx[i];
		if (yy<0 || H<=yy || xx<0 || W<=xx) continue;
		if (mass[xx][yy]!='1') continue;
		rec(xx, yy);
	}
}

int main()
{
	int count, i, j;
	string c;

	while ( cin>>mass[0] ) {
		for (i = 1; i < W; i++)
			cin>>mass[i];

		count = 0;
		for (i = 0; i < W; i++) {
			for (j = 0; j < H; j++) {
				if (mass[i][j] != '1') continue;
				count++;
				rec(i, j);
			}
		}
		cout<<count<<endl;
	}

	return 0;
}


#include<stdio.h>
#include<string.h>
int main()
{
    char x[100], y[100], z[100];
    scanf("%s %s %s", x, y, z);
    int lenA = strlen(x);
    int lenB = strlen(y);
    if(x[lenA - 1] == y[0] && y[lenB - 1] == z[0])
    {
        printf("YES\n");
    }
    else
    {
        printf("NO\n");
    }
    return 0;
}

#define _GLIBCXX_DEBUG
#include<bits/stdc++.h>
#include<algorithm>//next_permutation
#define rep(i,n) for (int i = 0;i < (n);i++)
#define all(v) v.begin(),v.end()
#define dec(n) cout << fixed << setprecision(n);
#define large "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define small "abcdefghijklmnopqrstuvwxyz"
using namespace std;
using ll = long long;
using P = pair<ll,ll>;
using vl = vector<ll>;
using vvl = vector<vl>;

ll gcd(ll a,ll b){
  if(b == 0) return a;
  return gcd(b , a % b);
}

ll mod(ll a){
  return (a % 1000000007);
}

ll lcm(ll a,ll b){
  return (a*b)/gcd(a,b);
}

ll nCr(ll n,ll r){
  if(r == 1) return n;
  else if(r == 0) return 1;
  else return nCr(n-1,r-1)*n/r;
}

int main(){
  ll num[] ={7,17,37,47,67,97,107,127,137,157,167,197,227,257,277,
          307,317,337,347,367,397,457,467,487,547,557,577,587,
          607,617,647,677,727,757,787,797,827,857,877,887,907,
          937,947,967,977,997,1087,1097,1117,1187,1217,1237,
          1277,1297,1307,1327};

  ll n; cin >> n;

  rep(i,n){
    cout << num[i];
    if(i == n) cout << endl;
    else cout << ' ';
  }

}


/*#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")*/
#include<bits/stdc++.h>
#define ll long long
#define inf 1000000005
#define put putchar('\n')
#define F(i,a,b) for (int i=(a);i<=(b);i++)
#define D(i,a,b) for (int i=(a);i>=(b);i--)
#define go(i,t) for (int i=head[t];i;i=Next[i])
#define sqr(x) ((x)*(x))
#define re register
#define mp make_pair
#define fi first
#define se second
#define pa pair<int,int>
#define pb push_back
#define be begin()
#define en end()
#define ret return puts("-1"),0;
#define mod 1000000007
#define N 500055
#define int ll
using namespace std;
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
inline int read(){char c=getchar();int tot=1;while ((c<'0'|| c>'9')&&c!='-') c=getchar();if (c=='-'){tot=-1;c=getchar();}
int sum=0;while (c>='0'&&c<='9'){sum=sum*10+c-'0';c=getchar();}return sum*tot;}
inline void wr(int x){if (x<0) {putchar('-');wr(-x);return;}if(x>=10)wr(x/10);putchar(x%10+'0');}
inline void wrn(int x){wr(x);put;}inline void wri(int x){wr(x);putchar(' ');}
inline void wrn(int x,int y){wri(x);wrn(y);}inline void wrn(int a,int b,int c){wri(a);wrn(b,c);}
int n,m,vis[N],co[N],I,P,Q;
int nedge,Next[N*2],head[N],to[N*2];
#define V to[i]
void add(int a,int b){
	Next[++nedge]=head[a];head[a]=nedge;to[nedge]=b;
}
void add_ne(int a,int b){add(a,b);add(b,a);}
bool dfs(int x){
	vis[x]=1;
	bool num=1;
	go(i,x){
		if (vis[V]) num&=(co[x]!=co[V]);
		else co[V]=co[x]^1,num&=dfs(V);
	}
	return num;
}
signed main(){
	n=read();m=read();
	F(i,1,m){
		add_ne(read(),read());
	}
	F(i,1,n){
		if (!vis[i]){
			if (head[i]==0) I++;
			else if (dfs(i)) Q++;
			else P++;
		}
	}
	wrn(I*I+I*(n-I)*2+P*Q*2+P*P+Q*Q*2);
	return 0;
}

#include <bits/stdc++.h>
#define fi first
#define se second
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define space putchar(' ')
#define enter putchar('\n')
#define eps 1e-10
#define MAXN 100005
//#define ivorysi
using namespace std;
typedef long long int64;
typedef unsigned int u32;
typedef double db;
template<class T>
void read(T &res) {
    res = 0;T f = 1;char c = getchar();
    while(c < '0' || c > '9') {
	if(c == '-') f = -1;
	c = getchar();
    }
    while(c >= '0' && c <= '9') {
	res = res * 10 +c - '0';
	c = getchar();
    }
    res *= f;
}
template<class T>
void out(T x) {
    if(x < 0) {x = -x;putchar('-');}
    if(x >= 10) {
	out(x / 10);
    }
    putchar('0' + x % 10);
}
int H,W;
char s[105][105];
int sum[105][105],a,b;
int dp[2][105][105][105],ans;
int query(int x1,int y1,int x2,int y2) {

    x2 = min(H,x2);y2 = min(W,y2);
    if(x1 > x2 || y1 > y2) return 0;
    return sum[x2][y2] - sum[x2][y1 - 1] - sum[x1 - 1][y2] + sum[x1 - 1][y1 - 1];
}
void update(int &x,int y) {
    x = max(x,y);
}
void Solve() {
    read(H);read(W);
    for(int i = 1 ; i <= H ; ++i) scanf("%s",s[i] + 1);
    for(int i = 1 ; i <= H ; ++i) {
	for(int j = 1 ; j <= W ; ++j) {
	    sum[i][j] = (s[i][j] == 'o');
	    sum[i][j] += sum[i][j - 1];
	    if(s[i][j] == 'E') {a = i;b = j;}
	}
    }
    for(int i = 1 ; i <= H ; ++i) {
	for(int j = 1 ; j <= W ; ++j) {
	    sum[i][j] += sum[i - 1][j];
	}
    }
    int cur = 0;
    dp[0][0][0][0] = 0;
    for(int i = 0 ; i < a ; ++i) {
	memset(dp[cur ^ 1],0,sizeof(dp[cur ^ 1]));
	for(int j = 0 ; j < b ; ++j) {
	    for(int k = 0 ; k <= H - a ; ++k) {
		for(int t = 0 ; t <= W - b ; ++t) {
		    ans = max(ans,dp[cur][j][k][t]);
		    int tmp = dp[cur][j][k][t];
		    if(k < a - i - 1) tmp += query(a - i - 1,max(b - j,t + 1),a - i - 1,min(b + t,W - j));
		    update(dp[cur ^ 1][j][k][t],tmp);
		    tmp = dp[cur][j][k][t];
		    if(t < b - j - 1) tmp += query(max(a - i,k + 1),b - j - 1,min(a + k,H - i),b - j - 1);
		    update(dp[cur][j + 1][k][t],tmp);
		    tmp = dp[cur][j][k][t];
		    if(H - i >= a + k + 1) tmp += query(a + k + 1,max(b - j,t + 1),a + k + 1,min(b + t,W - j));
		    update(dp[cur][j][k + 1][t],tmp);
		    tmp = dp[cur][j][k][t];
		    if(W - j >= b + t + 1) tmp += query(max(a - i,k + 1),b + t + 1,min(a + k,H - i),b + t + 1);
		    update(dp[cur][j][k][t + 1],tmp);
		}
	    }
	}
	cur ^= 1;
    }
    out(ans);enter;
}

int main() {
#ifdef ivorysi
    freopen("f1.in","r",stdin);
#endif
    Solve();
    return 0;
}


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

int main(void) {
  int N, Q; cin >> N >> Q;
  string S; cin >> S;
  vector<int> L(Q);
  vector<int> R(Q);
  vector<int> A(N);

  for (int i=0; i<Q; i++) {
    cin >> L[i] >> R[i];
  }

  int cnt = 0;
  A[0] = 0;
  for (int i=1; i<N; i++) {
    if (S[i] == 'C' && S[i-1] == 'A') cnt++;
    A[i] = cnt;
  }

  for (int i=0; i<Q; i++) {
    cout << A[R[i]-1] - A[L[i]-1] << endl;
  }

  return 0;
}

#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(v) v.begin(), v.end()
#define Graph vector< vector<int> >
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1000000007;

Graph G(100010);
vector<bool> seen(100010, false);
vector<int> prenum(100010), parent(100010), lowest(100010);

int id;

void dfs(int now, int prev){
    prenum[now] = lowest[now] = id;
    id++;
    seen[now] = true;

    rep(i, G[now].size()){
        int next = G[now][i];
        if(!seen[next]){
            parent[next] = now;
            dfs(next, now);
            lowest[now] = min(lowest[next], lowest[now]);
        }
        else if(next != prev){
            lowest[now] = min(lowest[now], prenum[next]);
        }
    }
}

int main(){
    int N, M;
    cin >> N >> M;
    rep(i, M){
        int s, t;
        cin >> s >> t;
        G[s].push_back(t);
        G[t].push_back(s);
    }

    id = 1;
    dfs(0, -1);

    set<int> ans;
    int root_p = 0;
    for(int i = 1; i < N; i++){
        int p = parent[i];
        if(p == 0) root_p++;
        else if(prenum[p] <= lowest[i]) ans.insert(p);
    }

    if(root_p >= 2) ans.insert(0);

    for(set<int>::iterator it = ans.begin(); it != ans.end(); it++){
        cout << *it << endl;
    }
}


#include<bits/stdc++.h>
#define all(x) (x).begin(),(x).end()
#define ll long long
#define rep(i,n) for(int i = 0; i < int(n); i++)
#define vi vector<int>
#define INF (1<<30)-1
using namespace std;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
template<class T> inline bool chmax(T &a, const T &b){ if(a<b) { a=b; return 1; } return 0; }
template<class T> inline bool chmin(T &a, const T &b){ if(b<a) { a=b; return 1; } return 0; }

int main(){
  cin.tie(0), ios::sync_with_stdio(false);
  const int MOD = 998244353;
  int n; cin >> n;
  map<int,int> mp;
  vi d(n);
  int mx = 0;
  rep(i,n){
    cin >> d[i];
    mp[d[i]]++;
    chmax(mx,d[i]);
  }
  if(mp[0]!=1 || d[0]!=0){
    cout << 0;
    return 0;
  }
  ll ans = 1;
  for(int i = 1; i <= mx; i++){
    // ll res = (ll)pow(mp[i-1],mp[i]);
    ll res = 1;
    rep(j,mp[i]){
      res *= mp[i-1];
      res %= MOD;
    }
    ans *= res;
    ans %= MOD;
  }
  cout << ans;
  cout << "\n";
  return 0;
}

/**
*    author:  souzai32
*    created: 13.08.2020 13:17:00
**/

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;

int main() {

    int n;
    cin >> n;
    vector<int> a(n);
    rep(i,n) cin >> a.at(i);

    sort(a.begin(),a.end());
    int c=0;
    for(int i=0; i<n; i++){
        if(a.at(i)<0){
            a.at(i)*=-1;
            c++;
        }
        else break;
    }

    sort(a.begin(),a.end());
    long long sum;
    if(c%2) sum=-a.at(0);
    else sum=a.at(0);
    for(int i=1; i<n; i++) sum+=a.at(i);

    cout << sum << endl;

    return 0;
}


//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define repd(i,a,b) for (int i=(a);i<(b);i++)
#define rep(i,n) repd(i,0,n)
typedef long long ll;
typedef long double lb;
#define int long long
#define double long double
#define endn "\n"
typedef pair<int,int> P;
template<class T> inline bool chmin(T& a, T b){if(a>b){a = b;return 1;}return 0;}
template<class T> inline bool chmax(T& a, T b){if(a<b){a = b;return 1;}return 0;}
const int MOD = 1000000007;
//const int MOD = 998244353;
const ll INF = 1e16;
const double EPS = 1e-10;
const double PI = 3.141592653589793;
const string abc="abcdefghijklmnopqrstuvwxyz";
const string ABC="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const pair<int,int> fd[] = {make_pair(1,0),make_pair(-1,0),make_pair(0,1),make_pair(0,-1)};

////////////////////////////////////////////////////////////////////
///////////////////////___modpow___////////////////////
ll modpow(ll a,  ll n, const ll &MOD = MOD){
  ll ret = n == 0 ? 1 : modpow(a, n/2, MOD);
  (ret *= ret) %= MOD;
  if(n%2)((ret *= a) %= MOD);
  return ret;
}
///////////////////////___modinv___////////////////////
ll modinv(ll d, const ll &MOD = MOD){
  return modpow(d, MOD-2, MOD);
}
///////////////////////___combination___////////////////////
vector<ll> fac, finv, inv;
void COMinit(const int MAX = 5000000, const ll &MOD = MOD){
  fac.resize(MAX);finv.resize(MAX);inv.resize(MAX);
  fac[0] = fac[1] = finv[0] = finv[1] = inv[1] = 1;
  repd(i,2,MAX){
    fac[i] = fac[i-1] * i % MOD;
    inv[i] = MOD - inv[MOD%i] * (MOD/i) % MOD;
    finv[i] = finv[i-1] * inv[i] % MOD;
  }
}
ll COM(int n, int k){
  if(n < k)return 0;
  if(n < 0 || k < 0)return 0;
  return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD;
}

///////////////////////////////////////////////////////////
int n,a[210000];
signed main(){
  cin>>n;bool b = true;
  rep(i,n)cin>>a[i];
  int ans = a[n-1], m = a[n-1]-1;
  for(int i = n-2;i >= 0;i--){
    if(m > a[i] || m > i){
      b = false;
    }
    if(a[i+1] != a[i]+1){
      ans += a[i];
    }
    m--;
  }
  if(b && a[0] == 0)cout << ans << endl;
  else cout << -1 << endl;
}

#include<iostream>
main(){
long a,b=-1,n,r;
std::cin>>n;
while(n--){
std::cin>>a;
if(a>b+1)return std::cout<<-1,0;
r+=a>b?1:a,b=a;
}
std::cout<<--r;
}


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

typedef long long ll;
typedef pair<int,int> pii;

long long MOD = 1000000000 + 7;

int main(){
  cout << setprecision(10);
  int N,Q; cin >> N >> Q;
  string S; cin >> S;

  vector<int> ans(N, 0);
  for(int i = 1; i < N; i++){
    if(S[i] == 'C' && S[i-1] == 'A'){
      ans[i] = 1;
    }
  }
  for(int i = 1; i < N; i++){
    ans[i] += ans[i-1];
    // cerr << "i: " << i << " ans[i]: " << ans[i] << endl;
  }

  while(Q--){
    int l,r; cin >> l >> r; l--; r--;
    int ret;
    if(l == 0){
      ret = ans[r];
    } else {
      ret = ans[r] - ans[l-1];
      if(S[l] == 'C' && S[l-1] == 'A'){
        ret--;
      }
    }
    cout << ret << endl;
  }

}

#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define rep(i,n) for (int i=0;i<(int)(n);i++)
#define codefor int test;scanf("%d",&test);while(test--)
#define yn(ans) cout<<(ans?"Yes":"No")<<endl
#define YN(ans) cout<<(ans?"YES":"NO")<<endl
#define umap unordered_map
#define uset unordered_set
using namespace std;
using ll = long long;
const int MOD=1000000007;
//入力系
void scan(int& a){scanf("%d",&a);}
void scan(long long& a){scanf("%lld",&a);}
template<class T> void scan(T& a){cin>>a;}
template<class T> void scan(vector<T>& vec){for(auto&& it:vec)scan(it);}
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){scan(head);in(tail...);}
//出力系
void print(const int& a){printf("%d",a);}
void print(const long long& a){printf("%lld",a);}
void print(const double& a){printf("%.15lf",a);}
template<class T> void print(const T& a){cout<<a;}
template<class T> void print(const vector<T>& vec){if(vec.empty())return;print(vec[0]);for(auto it=vec.begin();++it!= vec.end();){putchar(' ');print(*it);}}
void out(){putchar('\n');}
template<class T> void out(const T& t){print(t);putchar('\n');}
template <class Head, class... Tail> void out(const Head& head,const Tail&... tail){print(head);putchar(' ');out(tail...);}
//デバッグ系
template<class T> void dprint(const T& a){cerr<<a;}
template<class T> void dprint(const vector<T>& vec){if(vec.empty())return;cerr<<vec[0];for(auto it=vec.begin();++it!= vec.end();){cerr<<" "<<*it;}}
void debug(){cerr<<endl;}
template<class T> void debug(const T& t){dprint(t);cerr<<endl;}
template <class Head, class... Tail> void debug(const Head& head, const Tail&... tail){dprint(head);cerr<<" ";debug(tail...);}

int main(){
    int  n,q;
    ll ans=0;
    string s;
    in(n,q,s);
    vector<ll> vec(n);
    vec[0]=0;
    for(int i=1;i<n;i++){
        if(s[i-1]=='A'&&s[i]=='C'){
            ans++;
        }
        vec[i]=ans;
    }
    int l,r;
    rep(i,q){
        in(l,r);
        out(vec[r-1]-vec[l-1]);
    }
}