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

#define gcu getchar_unlocked
#define pcu putchar_unlocked
#define _il inline
#define _in _il int in
#define _sc _il bool scan
_in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();
	do{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;} //&&c<='9'
_in() {return in(gcu());}
_sc(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}
_sc(char &c){c=gcu();gcu();return c!=EOF;}
//_sc(string &s){int c;s="";
//	for(;;){c=gcu();if(c=='\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}
template <typename H,typename... T> _sc(H &h, T&&... t){return scan(h)&&scan(t...);}
#define _vo _il void out
#define _vl _il void outl
template <typename T>
_vo(T n){static char buf[20];char *p=buf;
	if(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;
	while (p!=buf)pcu(*--p);}
_vo(const char *s){while(*s)pcu(*s++);}
_vo(char c){pcu(c);}
//_vo(string &s){for (char c: s) pcu(c);}
template <typename H,typename... T> _vo(H&& h, T&&... t){out(h);out(move(t)...);}
//template <typename T> _vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);out('\n');}
_vl(){out('\n');}
template <typename... T> _vl(T&&... t){out(move(t)...);outl();}

template<int N>
struct sieve {
	bool s[N];
	constexpr sieve() : s() {
		for (int i = 0; i < N; i++)
			s[i] = true;
		for (int i = 4; i < N; i += 2)
			s[i] = false;
		for (int i = 9; i < N; i += 6)
			s[i] = false;
		for (int i = 6, e = sqrt(N); i <= e; i += 6) {
			for (int j : {i - 1, i + 1})
				if (s[j])
					for (int k = j * j; k < N; k += j)
						s[k] = false;
		}
	}
};

template<int N>
struct twin {
	int t[N/10], l;
	constexpr twin() : t(), l(1) {
		sieve<N> s;
		t[0] = 5;
		for (int i = 0; i < N; i++)
			if (s.s[i - 2] && s.s[i])
				t[l++] = i;
	}
};

int main() {
	enum {N = 10001};
	twin<N> t;
	for (int n; (n = in());) {
		auto r = upper_bound(t.t, t.t + t.l, n) - 1;
		outl(*r - 2, ' ', *r);
	}
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Edge {
	ll to;     // 辺の行き先
	ll weight; // 辺の重み
	Edge(ll t, ll w) : to(t), weight(w) { }
};
using Graph = vector<vector<Edge>>;

int main() {

    // 頂点数と辺数
    ll n, m; cin >> n;
    m = n - 1;

    // グラフ入力受取 (ここでは重み付き無向グラフを想定)
    Graph G(n);
    for (ll i = 0; i < m; ++i) {
        ll a, b, c;
        cin >> a >> b >> c;
        a--;
        b--;
        G[a].push_back(Edge(b, c));
        G[b].push_back(Edge(a, c));
    }

    ll q, k; cin >> q >> k;
    k--;

    // BFS のためのデータ構造
    vector<ll> dist(n, -1); // 全頂点を「未訪問」に初期化
    queue<Edge> que;

    // 初期条件 (頂点 k を初期ノードとする)
    dist[k] = 0;
    que.push(Edge(k, 0)); // 0 を橙色頂点にする

    // BFS 開始 (キューが空になるまで探索を行う)
    while (!que.empty()) {
        Edge v = que.front(); // キューから先頭頂点を取り出す
        que.pop();

        // v から辿れる頂点をすべて調べる
        for (Edge new_v : G[v.to]) {
            if (dist[new_v.to] != -1) continue; // すでに発見済みの頂点は探索しない

            // 新たな白色頂点 new_v について距離情報を更新してキューに追加する
            dist[new_v.to] = dist[v.to] + new_v.weight;
            que.push(new_v);
        }
    }

    for (ll i = 0; i < q; i++) {
        ll x, y; cin >> x >> y;
        x--;
        y--;
        cout << dist[x] + dist[y] << endl;
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
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 ll = long long;
using P = pair<int, int>;
ll GCD(ll a, ll b) { return b?GCD(b, a%b):a; }
ll LCM(ll a, ll b) { return a/GCD(a, b)*b; }

int n, u, v;
vector< vector<int> > graphlist(100100, vector<int>());
vector<int> takahashi(100100, -1);
vector<int> aoki(100100, -1);
struct posdata {
    int p; int dist;
};

int main() {
    cin >> n >> u >> v;
    u--; v--;
    takahashi.at(u) = 0; aoki.at(v) = 0;
    for(int i = 0; i < n-1; ++i) {
        int aa, bb; cin >> aa >> bb;
        aa--; bb--;
        graphlist.at(aa).emplace_back(bb);
        graphlist.at(bb).emplace_back(aa);
    }

    queue<posdata> tque;
    posdata tfirst;
    tfirst.p = u; tfirst.dist = 0;
    tque.push(tfirst);
    while(!tque.empty()) {
        posdata now = tque.front();
        tque.pop();
        for(int i = 0; i < (int)graphlist.at(now.p).size(); ++i) {
            int np = graphlist.at(now.p).at(i);
            int ndist = now.dist+1;
            if(takahashi.at(np) == -1) {
                takahashi.at(np) = ndist;
                posdata next;
                next.p = np; next.dist = ndist;
                tque.push(next);
            }
        }
    }

    queue<posdata> aque;
    posdata afirst;
    afirst.p = v; afirst.dist = 0;
    aque.push(afirst);
    while(!aque.empty()) {
        posdata now = aque.front();
        aque.pop();
        for(int i = 0; i < (int)graphlist.at(now.p).size(); ++i) {
            int np = graphlist.at(now.p).at(i);
            int ndist = now.dist+1;
            if(aoki.at(np) == -1) {
                aoki.at(np) = ndist;
                posdata next;
                next.p = np; next.dist = ndist;
                aque.push(next);
            }
        }
    }

    int amax = 0;
    for(int i = 0; i < n; ++i) {
        if(aoki.at(i) > takahashi.at(i)) {
            chmax(amax, aoki.at(i));
        }
    }

    cout << amax-1 << endl;
}


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

const ll INF = 1LL<<62;
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; }
// 多次元 vector 生成
template<class T>
vector<T> make_vec(size_t a){
    return vector<T>(a);
}
template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

const int MOD = 1000000007;

int ans = 100000000;

int main(){
    int N; cin >> N;
    vector<int> A(N,0);
    rep(i,N) cin >> A[i];

    vector<int> A2(N+2,0);
    rep(i,N) A2[i+1] = A[i];
    A2[N+1] = 0;

    ll total = 0;
    rep(i,N+1){
        total += abs(A2[i] - A2[i+1]);
    }

    ll ans;
    rep(i,N){
        ans = total - abs(A2[i]-A2[i+1]) - abs(A2[i+1]-A2[i+2]) + abs(A2[i]-A2[i+2]);
        cout << ans << endl;
    }
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<long long, long long> P;
struct edge{long long to,cost;};
const int inf = 1 << 27;
const long long INF = 1LL << 60;
const int COMBMAX = 1001001;
const long long MOD = 1000000007;
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define eachdo(v, e) for(const auto& e : (v))
#define all(v) (v).begin(), (v).end()
#define lower_index(v, e) (long long)distance((v).begin(), lower_bound((v).begin(), (v).end(), e))
#define upper_index(v, e) (long long)distance((v).begin(), upper_bound((v).begin(), (v).end(), e))
long long mpow(long long a, long long n, long long mod = MOD){long long res = 1; while(n > 0){if(n & 1)res = res * a % mod; a = a * a % mod; n >>= 1;} return res;}
void yn(bool j){cout << (j ? "Yes" : "No") << endl; return;}
template<class Head> void pt(Head&& head){cout << head << endl; return;}
template<class Head, class... Tail> void pt(Head&& head, Tail&&... tail){cout << head << " "; pt(forward<Tail>(tail)...);}
template<class T> void debug(T v){rep(i, v.size()) cout << v[i] << " " ; cout << endl;}
template<class T> void debug2(T v){rep(i, v.size()){rep(j, v[i].size()) cout << v[i][j] << " " ; cout << endl;}}
template<class T1, class T2> long long bcount(T1 v, T2 a){return upper_index(v, a) - lower_index(v, a);}
template<class T1, class T2> inline bool chmin(T1 &a, T2 b){if(a > b){a = b; return true;} return false;}
template<class T1, class T2> inline bool chmax(T1 &a, T2 b){if(a < b){a = b; return true;} return false;}
template<class T1, class T2> void sortTwoVecter(vector<T1> &f, vector<T2> &s, bool isReverse = false){
    vector<pair<T1, T2>> p;
    rep(i, f.size()) p.emplace_back(make_pair(f[i], s[i]));
    if (!isReverse) sort(p.begin(), p.end());
    else sort(p.rbegin(), p.rend());
    rep(i, f.size()) tie(f[i], s[i]) = p[i];
    return;
}

int main(){
    ll N; cin >> N;
    vector<ll> a(N + 2, 0), s(N + 2, 0);
    rep(i, N){
        cin >> a[i + 1];
        s[i + 1] = s[i] + abs(a[i] - a[i + 1]);
    }
    s[N + 1] = s[N] + abs(a[N] - a[N + 1]);

    rep(i, N){
        pt(s[i] + abs(a[i + 2] - a[i]) + s[N + 1] - s[i + 2]);
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
template <typename T>
inline void readin(T &x) {
    x = 0;
    T fh = 1;
    char ch = getchar();
    for (; !isdigit(ch); ch = getchar()) if (ch == '-') fh = -1;
    for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48);
    x *= fh;
}
inline void d_read(double &x) {
    x = 0.0;
    int fh = 1;
    char ch = getchar();
    for (; !isdigit(ch); ch = getchar()) if (ch == '-') fh = -1;
    for (; isdigit(ch); ch = getchar()) x = x * 10 + (ch ^ 48);
    if (ch == '.') {
        double num = 1.0;
        ch = getchar();
        for (; isdigit(ch); ch = getchar()) x = x + (num /= 10) * (ch ^ 48);
    }
    x *= fh;
}
template <typename T>
inline void wt(T x) {
    if (x > 9) wt(x / 10);
    putchar(x % 10 + 48);
}
template <typename T>
inline void writeln(T x, char c) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    wt(x);
    putchar(c);
}
const int N = 2e5 + 5;
int a[N << 2], t[N << 2], tg[N << 2];
inline void up(int p) {
    a[p] = min(a[p << 1], a[p << 1 | 1]);
    t[p] = min(t[p << 1], t[p << 1 | 1]);
}
inline void work(int p, int l, int r, int k) {
    a[p] = k;
    t[p] = k + l;
    tg[p] = k;
}
inline void build(int p, int l, int r) {
    tg[p] = -1e9;
    if (l == r) {
        a[p] = -l;
        t[p] = a[p] + l;
    }
    else {
        int mid = l + r >> 1;
        build(p << 1, l, mid);
        build(p << 1 | 1, mid + 1, r);
        up(p);
    }
}
inline void down(int p, int l, int r) {
    if (tg[p] != -1e9) {
        int mid = l + r >> 1;
        a[p << 1] = a[p << 1 | 1] = tg[p];
        tg[p << 1] = tg[p << 1 | 1] = tg[p];
        t[p << 1] = tg[p] + l;
        t[p << 1 | 1] = tg[p] + mid + 1;
        tg[p] = -1e9;
    }
}
int sum;
inline void ask(int p, int l, int r, int pos) {
    if (l == pos && pos == r) {
        sum = a[p];
    }
    else {
        down(p, l, r);
        int mid = l + r >> 1;
        if (pos <= mid) ask(p << 1, l, mid, pos);
        else ask(p << 1 | 1, mid + 1, r, pos);
    }
}
inline void modify(int p, int l, int r, int ql, int qr, int k) {
    if (l >= ql && r <= qr) {
        a[p] = k;
        t[p] = a[p] + l;
        tg[p] = k;
    }
    else {
        down(p, l, r);
        int mid = l + r >> 1;
        if (ql <= mid) modify(p << 1, l, mid, ql, qr, k);
        if (mid < qr) modify(p << 1 | 1, mid + 1, r, ql, qr, k);
        up(p);
    }
}
int n, m;
int main() {
    readin(n); readin(m);
    int x, y;
    build(1, 1, m);
    for (int i = 1; i <= n; i ++) {
        readin(x); readin(y);
        sum = 1e8;
        if (x > 1) ask(1, 1, m, x - 1);
        modify(1, 1, m, x, y, sum);
        if (t[1] + i >= 1e8) puts("-1");
        else writeln(t[1] + i, '\n');
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
template<class C>constexpr int sz(const C&c){return int(c.size());}
using ll=long long;constexpr const char nl='\n',sp=' ';

int main() {
  // freopen("in.txt", "r", stdin);
  // freopen("out.txt", "w", stdout);
  // freopen("err.txt", "w", stderr);
  ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  int H, W;
  cin >> H >> W;
  map<int, int> S, freq;
  for (int i = 0; i < W; i++) {
    S[i] = i;
    freq[0]++;
  }
  for (int i = 0; i < H; i++) {
    int A, B;
    cin >> A >> B;
    --A; --B;
    int mx = -1;
    while (true) {
      auto it = S.upper_bound(B);
      if (it == S.begin()) break;
      --it;
      if (it->first < A) break;
      mx = max(mx, it->second);
      if (--freq[it->first - it->second] == 0) freq.erase(it->first - it->second);
      S.erase(it);
    }
    if (mx != -1 && B + 1 != W) {
      if (S.count(B + 1)) {
        if (--freq[B + 1 - S[B + 1]] == 0) freq.erase(B + 1 - S[B + 1]);
        S[B + 1] = max(S[B + 1], mx);
      } else S[B + 1] = mx;
      freq[B + 1 - S[B + 1]]++;
    }
    if (freq.empty()) cout << -1 << nl;
    else cout << (i + 1) + freq.begin()->first << nl;
  }
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    int N,A,B;
    cin>>N;
    if(N==1){
        cout<<"Hello World";
    }
    if(N==2){
        cin>>A>>B;
        cout<<A+B;
    }

}

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

int main() {

	ll x; cin >> x;
	ll ans = 0;
	ll quo = x / 11;
	ll mod = x % 11;
	if (mod == 0) {
		ans = quo * 2;
	}
	else if (1 <= mod && mod <= 6) {
		ans = quo * 2 + 1;
	}
	else { // 6 < mod <= 11
		ans = quo * 2 + 2;
	}

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


#include <algorithm>
#include <iostream>
using namespace std;
static const int MAX = 200000;

static const int sentinel = 1000000000;
long int ninvention = 0;

int 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] = sentinel;
  R[n2] = sentinel;

  int i = 0, j = 0;
  for (int k = left; k < right; k++) {
    if (L[i] <= R[j]) {
      A[k] = L[i];
      i++;
    } else {
      ninvention += max(0, n1 - i);
      A[k] = R[j];
      j++;
    }
  }
}

int 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 data[MAX];
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> data[i];
  }
  mergeSort(data, 0, n);

  cout << ninvention << endl;
}

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

using namespace std;

int main(){

	int in;

	cin >> in;

	int out = static_cast<int>(pow(static_cast<double>(in), 3.0));

	cout << out << endl;

	return 0;
}


// https://atcoder.jp/contests/arc069/tasks/arc069_b

#include "algorithm"
#include "bitset"
#include "cmath"
#include "functional"
#include "iomanip"
#include "iostream"
#include "map"
#include "numeric"
#include "queue"
#include "set"
#include "string"
#include "vector"
#define rep(i, to) for (ll i = 0; i < (to); ++i)
#define rep1(i, to) for (ll i = 1; i <= (to); ++i)
#define repf(i, from, to) for (ll i = from; i < (to); ++i)
#define repr(i, from) for (ll i = from - 1; i >= 0; --i)
#define all(vec) vec.begin(), vec.end()
#define unless(cond) if (!(cond))
#define fi first
#define se second
using namespace std;
typedef long long ll;
template <typename T>
using V = vector<T>;
using VL = V<ll>;
using VVL = V<VL>;
template <typename T, typename U>
using P = pair<T, U>;
using PL = P<ll, ll>;
using VPL = V<PL>;
template <typename T>
inline bool chmax(T& a, T b);
template <typename T>
inline bool chmin(T& a, T b);
void print_ints(vector<ll> v);
template <typename T>
void drop(T a);

const ll INF = 1e18;

void solve() {
  ll N;
  string S;
  cin >> N >> S;

  auto get_next = [](char prev, char cur, char ch) -> char {
    if (cur == 'S' && ch == 'o') return prev == 'S' ? 'S' : 'W';
    if (cur == 'S' && ch == 'x') return prev == 'S' ? 'W' : 'S';
    if (cur == 'W' && ch == 'o') return prev == 'S' ? 'W' : 'S';
    if (cur == 'W' && ch == 'x') return prev == 'S' ? 'S' : 'W';
  };

  auto to_s = [](ll v) -> char { return v == 0 ? 'S' : 'W'; };

  rep(f, 2) rep(s, 2) {
    string res;

    res.push_back(to_s(f));
    res.push_back(to_s(s));

    repf(cur_i, 1, N - 1) {
      char n = get_next(res[cur_i - 1], res[cur_i], S[cur_i]);
      res.push_back(n);
    }

    if (get_next(res[N - 2], res[N - 1], S[N - 1]) == res[0] &&
        get_next(res[N - 1], res[0], S[0]) == res[1])
      drop(res);
  }

  drop(-1);
}

struct exit_exception : public std::exception {
  const char* what() const throw() { return "Exited"; }
};

#ifndef TEST
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  try {
    solve();
  } catch (exit_exception& e) {
  }

  return 0;
}
#endif

template <typename T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}

template <typename T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}

void print_ints(vector<ll> v) {
  rep(i, v.size()) {
    if (i > 0) {
      cout << " ";
    }

    cout << v[i];
  }

  cout << endl;
}

template <typename T>
void drop(T res) {
  cout << res << endl;
  throw exit_exception();
}

//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using st=string;
using ch=char;
typedef pair<ll,ll> P;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<P> vP;
typedef vector<ch> vc;
typedef vector<vc> vvc;
#define FOR(i,a,b) for(ll i=a;i<b;i++)
#define rep(i,n) FOR(i,0,n)
#define ROF(i,a,b) for(ll i=a;i>=b;i--)
#define per(i,a) ROF(i,a,0)
#define pb push_back
#define mp make_pair
const ll MOD=1000000007;
const ll MOD2=998244353;
const ld PI=acos(-1);
const ll INF=1e18;
st abc="abcdefghijklmnopqrstuvwxyz";
st ABC="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
struct edge{ll to,cost;};

ll n;
st s;
vc a;
bool b;

void srch(ll z,ll f){
  if(z==0){
    a[0]='S';
  }
  else{
    a[0]='W';
  }
  if(f==0){
    a[1]='S';
  }
  else{
    a[1]='W';
  }
  FOR(i,1,n-1){
    if((a[i]=='S'&&s[i]=='o')||(a[i]=='W'&&s[i]=='x')){
      a[i+1]=a[i-1];
    }
    else{
      if(a[i-1]=='W'){
        a[i+1]='S';
      }
      else{
        a[i+1]='W';
      }
    }
  }
  b=true;
  rep(i,2){
    ll cnt=0;
    if(a[(n-1+i)%n]=='W'){
      cnt++;
    }
    if(s[(n-1+i)%n]=='x'){
      cnt++;
    }
    if(a[(n-2+i)%n]!=a[i%n]){
      cnt++;
    }
    if(cnt%2==1){
      b=false;
    }
  }
}
int main(){
  cin >> n >> s;
  a.resize(n);
  b=false;
  srch(0,0);
  if(b){
    rep(i,n){
      cout << a[i];
    }
    return 0;
  }
  srch(0,1);
  if(b){
    rep(i,n){
      cout << a[i];
    }
    return 0;
  }
  srch(1,0);
  if(b){
    rep(i,n){
      cout << a[i];
    }
    return 0;
  }
  srch(1,1);
  if(b){
    rep(i,n){
      cout << a[i];
    }
    return 0;
  }
  cout << -1 << endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<int> vi;
typedef vector<ll> vll;
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define INF 1000000000
#define LLINF 100000000000000000ll
#define sz(x) ((int)(x).size())
#define fi first
#define sec second
#define all(x) (x).begin(),(x).end()
#define sq(x) ((x)*(x))
#define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++)
#define EQ(a,b) (abs((a)-(b))<eps)
template<class T> void chmin(T& a,const T& b){if(a>b)a=b;}
template<class T> void chmax(T& a,const T& b){if(a<b)a=b;}
int H,W;
string s[2010];
int dp[2010][2010];
int L[2010],R[2010];
int max_rect(vector<int> v){
	stack<int> st;
	for(int i=0;i<v.size();i++){
		while(!st.empty()&&v[st.top()]>=v[i])st.pop();
		if(st.empty())L[i]=-1;
		else L[i]=st.top();
		st.push(i);
	}
	while(!st.empty())st.pop();
	for(int i=v.size()-1;i>=0;i--){
		while(!st.empty()&&v[st.top()]>=v[i])st.pop();
		if(st.empty())R[i]=v.size();
		else R[i]=st.top();
		st.push(i);
	}
	int res = 0;
	for(int i=0;i<v.size();i++){
		if(L[i]==-1)res = max(res,(R[i]-L[i]-1)*v[i]);
		else res = max(res,(R[i]-L[i])*v[i]);
	}
	return res;
}
int main(){
	cin >> H >> W;
	for(int i=0;i<H;i++)cin >> s[i];
	for(int i=0;i<W;i++)dp[0][i]=W-i;
	for(int i=1;i<H;i++){
		dp[i][W-1]=1;
		for(int j=W-2;j>=0;j--){
			if(s[i][j]==s[i-1][j]&&s[i][j+1]==s[i-1][j+1])dp[i][j]=dp[i][j+1]+1;
			else if(s[i][j]!=s[i-1][j]&&s[i][j+1]!=s[i-1][j+1])dp[i][j]=dp[i][j+1]+1;
			else dp[i][j]=1;
		}
	}
	/*for(int i=0;i<H;i++){
		for(int j=0;j<W;j++){
			cout << dp[i][j] << ' ';
		}
		cout << endl;
	}*/
	int ans = 0;
	for(int j=0;j<W;j++){
		vector<int> v;
		for(int i=0;i<H;i++){
			v.pb(dp[i][j]);
		}
		ans = max(ans,max_rect(v));
	}
	cout << ans << endl;
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define int long long
#define FOR(i, a, b) for(ll i = (a); i < (b); ++i)
#define FORR(i, a, b) for(ll i = (a); i > (b); --i)
#define REP(i, n) for(ll i = 0; i < (n); ++i)
#define REPR(i, n) for(ll i = n; i >= 0; i--)
#define FOREACH(x, a) for(auto &(x) : (a))
#define VECCIN(x)                                                              \
    for(auto &youso_ : (x)) cin >> youso_
#define bitcnt __builtin_popcount
#define SZ(x) ((ll)(x).size())
#define fi first
#define se second
#define All(a) (a).begin(), (a).end()
template <typename T = long long> inline T IN() {
    T x;
    cin >> x;
    return (x);
}
inline void CIN() {}
template <class Head, class... Tail>
inline void CIN(Head &&head, Tail &&... tail) {
    cin >> head;
    CIN(move(tail)...);
}
#define CCIN(...)                                                              \
    char __VA_ARGS__;                                                          \
    CIN(__VA_ARGS__)
#define DCIN(...)                                                              \
    double __VA_ARGS__;                                                        \
    CIN(__VA_ARGS__)
#define LCIN(...)                                                              \
    ll __VA_ARGS__;                                                            \
    CIN(__VA_ARGS__)
#define SCIN(...)                                                              \
    string __VA_ARGS__;                                                        \
    CIN(__VA_ARGS__)
#define Yes(a) cout << (a ? "Yes" : "No") << "\n"
#define YES(a) cout << (a ? "YES" : "NO") << "\n"
#define Printv(v)                                                              \
    {                                                                          \
        FOREACH(x, v) { cout << x << " "; }                                    \
        cout << "\n";                                                          \
    }
template <typename T = string> inline void eputs(T s) {
    cout << s << "\n";
    exit(0);
}
template <typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val) {
    std::fill((T *)array, (T *)(array + N), val);
}
template <typename T> using PQG = priority_queue<T, vector<T>, greater<T>>;
template <typename T> using PQ = priority_queue<T>;

typedef long long ll;
typedef pair<ll, ll> PL;
typedef vector<PL> VPL;
typedef vector<ll> VL;
typedef vector<VL> VVL;
typedef vector<double> VD;

const int INF = 1e9;
const int MOD = 1e9 + 7;
const double PI = atan(1.0) * 4.0;
// const int MOD = 998244353;
const ll LINF = 9e18;
const ll dx[] = {1, 0, -1, 0};
const ll dy[] = {0, 1, 0, -1};

void cinfast() {
    cin.tie(0);
    ios::sync_with_stdio(false);
}

ll S[2000][2000], sum[2020][2020], csum[2020][2020], rsum[2020][2020];

signed main() {
    cinfast();
    LCIN(N, M, Q);
    REP(i, N) REP(j, M) {
        CCIN(s);
        S[i][j] = (s == '1');
        sum[i + 1][j + 1] +=
            sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + S[i][j];
        if(j)
            rsum[i + 1][j + 1] += rsum[i + 1][j] + rsum[i][j + 1] - rsum[i][j] +
                                  (S[i][j] & S[i][j - 1]);
        if(i)
            csum[i + 1][j + 1] += csum[i + 1][j] + csum[i][j + 1] - csum[i][j] +
                                  (S[i][j] & S[i - 1][j]);
    }
    REP(i, Q) {
        LCIN(x1, y1, x2, y2);
        x1--, y1--, x2--, y2--;
        ll ans = 0;
        ans += sum[x2 + 1][y2 + 1] - sum[x1][y2 + 1] - sum[x2 + 1][y1] +
               sum[x1][y1];
        ans -= rsum[x2 + 1][y2 + 1] - rsum[x1][y2 + 1] - rsum[x2 + 1][y1 + 1] +
               rsum[x1][y1 + 1];
        ans -= csum[x2 + 1][y2 + 1] - csum[x1 + 1][y2 + 1] - csum[x2 + 1][y1] +
               csum[x1 + 1][y1];
        cout << ans << "\n";
    }
}


#include <bits/stdc++.h>

using namespace std;

#define endl '\n'
#define Opy ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)

typedef long long ll;

int main()
{
    //Opy;

/*-------------------------------------------------
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
-------------------------------------------------*/
    ll a, h = 0;

    cin>> a;

    h += (a - (a % 500)) * 2;

    a %= 500;

    h += a - (a % 5);

    cout<< h<< endl;

    return 0;
}

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

int main() {
  ll X;
  cin >> X;

  ll c1=0;
  ll c2=0;
  while(X >= 500){
    X -= 500;
    c1++;
  }
  while(X >= 5){
    X -= 5;
    c2++;
  }
  cout << c1*1000+c2*5 << endl;
}


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

ll N= 998244353;

ll m_pow(ll n, ll k){
    if(k==0) return 1;
    else{
        ll a = (m_pow(n,k/2)*m_pow(n,k/2))%N;
        if(k%2==0) return a;
        else return (a*n)%N;
    }
}

int main(){
    ll n,m,k;
    cin >> n >> m >> k;
    vector<ll> mod_pow(n,1),combi(k+1,1);
    for(int i=1; i<n; i++){
        mod_pow.at(i) = mod_pow.at(i-1)*(m-1);
        mod_pow.at(i) %= N;
        if(i>k) continue;
        combi.at(i) = ((n-i)*combi.at(i-1))%N;
        combi.at(i) *= m_pow(i,N-2);
        combi.at(i) %= N;
    }
    ll ans = 0;
    for(int i=0; i<=k; i++){
        ll plus= (m*mod_pow.at(n-1-i))%N;
        plus = (plus*combi.at(i))%N;
        ans += plus;
        ans %= N;
    }
    cout << ans << endl;
    /*
    for(int i=0; i<k+1; i++){
        cout << combi.at(i) << endl;
    }*/

}

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

const int N = 2e5 + 5;
const int MOD = 1e9 + 7;

int n;
ll ar[N], sum[N];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> ar[i];
        sum[i] = ar[i];
    }
    for (int i = n - 1; i > 0; i--) {
        sum[i] += sum[i + 1];
        sum[i] %= MOD;
    }
    ll ans = 0;
    for (int i = 1; i <= n; i++) {
        ans += ar[i] * sum[i + 1] % MOD;
        ans %= MOD;
    }
    cout << ans << '\n';
    return 0;
}


#include <stdio.h>
int main(){

	char stringa[120];
	char stringb[120];

	scanf ("%s %s", &stringa, &stringb);
	printf ("%s%s", stringb, stringa);

	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...);
}

#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

void solve() {
  string s, t;
  cin >> s >> t;
  t += s;
  cout << t << "\n";
  debug(s);
  debug(t);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  solve();
  return 0;
}


#include "bits/stdc++.h"
using namespace std;
#define ll long long int
#define rep(i,n) for( int i = 0; i < n; i++ )
#define rrep(i,n) for( int i = n; i >= 0; i-- )
#define REP(i,s,t) for( int i = s; i <= t; i++ )
#define RREP(i,s,t) for( int i = s; i >= t; i-- )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 1000000000000000000
#define int long long
int x[100010], y[100010];
int n, m;
int sumx[100010], sumy[100010];

signed main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n >> m;
    rep(i, n) {
        cin >> x[i];
        sumx[i + 1] = (sumx[i + 1] + x[i] + sumx[i]) % mod;
    }
    rep(i, m) {
        cin >> y[i];
        sumy[i + 1] = (sumy[i + 1] + y[i] + sumy[i]) % mod;
    }
    int ansX = 0, ansY = 0;
    rep(i, n - 1) {
        ansX = (ansX + (-x[i] * (n - i - 1)) % mod + (sumx[n] - sumx[i + 1]) % mod + mod) % mod ;
        //cout << -x[i] * (n - i - 1)  <<" " << (sumx[n] - sumx[i + 1]) << endl;
    }
    rep(i, m - 1) {
        ansY = (ansY + (-y[i] * (m - i - 1)) % mod + (sumy[m] - sumy[i + 1]) % mod + mod) % mod;
    }
    cout << (ansX * ansY) % mod << endl;

    return 0;
}

#include <iostream>
#include <cmath>
#include <vector>
#include <bitset>
#include <string>
#include <utility>
#include <queue>
#include <algorithm>

using namespace std;
long long int mpown(long long int m, int n);

int bitCount(int bits);
int main()
{
    int n,k;
    cin >> n >>k;
    vector<long long int> v(n);
    for(int i=0;i<n;i++)cin >> v.at(i);
    // vector<vector<long long int>> dp(n+1,vector<long long int>(n+1,0));
    // vector<vector<long long int>> dpm(n+1,vector<long long int>(n+1,0));
    // vector<vector<long long int>> dpmn(n+1,vector<long long int>(n+1,0));
    // dp.at(i).at(j) : 左からi個，右からj個とったときの価値の合計
    // dpmn.at(i).at(j) : 左からi個，右からj個とったときの負の宝石の数
    // dpm.at(i).at(j) : 左からi個，右からj個とったときの負の価値の合計
    int r = min(n,k);
    priority_queue<long long int> mns;
    long long int sv=0;
    long long int temp;
    long long int ans=(-1000000000000);
    for(int a=0;a<=n;a++){
        for(int b=0;b<=r-a;b++){

            sv=0;
            priority_queue<long long int> mns;
            for(int i=0;i<a;i++){
                sv+=v.at(i);
                if(v.at(i)<0)
                mns.push(-v.at(i));
            }
            for(int j=0;j<b;j++){
                sv+=v.at(n-j-1);
                if(v.at(n-j-1)<0)
                mns.push(-v.at(n-j-1));
            }
            for(int i=0;i<k-(a+b);i++){
                if(mns.empty()){break;}
                sv+=mns.top();
                mns.pop();
            }

            if(ans<sv){ans=sv;
            // cout << a << " " << b << endl;
            }
        }
    }
    cout << ans << endl;
}

int bitCount(int bits)
{
    bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555); //  2bitごとに計算
    bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333); //  4bitごとに計算
    bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f); //  8bitごとに計算
    bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff); //  16ビットごとに計算
    return (bits & 0x0000ffff) + (bits >> 16);             //  32ビット分を計算
}
long long int mpown(long long int m, int n)
{
    if (n == 0)
        return 1;
    else if (n == 1)
        return m;
    else
    {
        long long int temp = mpown(m, n / 2);
        return temp * temp * (n & 1 ? m : 1);
    }
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstdlib>
#include <vector>
#define R register
#define IN inline
#define gc getchar()
#define ll long long
#define MX 105
template <class T>
IN void in(T &x)
{
	x = 0; R char c = gc;
	for (; !isdigit(c); c = gc);
	for (;  isdigit(c); c = gc)
	x = (x << 1) + (x << 3) + c - 48;
}
int n, sum;
std::vector <int> eve, odd;
int main(void)
{
	in(sum), in(n);
	int foo;
	for (R int i = 1; i <= n; ++i)
	{
		in(foo);
		if (foo & 1) odd.push_back(foo);
		else eve.push_back(foo);
	}
	if (n == 1)
	{
		if (sum == 1) printf("1\n1\n1");
		else printf("%d\n2\n%d %d", sum, 1, sum - 1);
		return 0;
	}
	if (odd.size() > 2) return puts("Impossible"), 0;
	else if (odd.size() == 2)
	{
		if (odd[0] > odd[1]) std::swap(odd[0], odd[1]);
		printf("%d ", odd[0]);
		for (auto i : eve) printf("%d ", i);
		printf("%d\n", odd[1]);
		odd[0]--, odd[1]++;
		if (!odd[0]) printf("%d\n", n - 1);
		else printf("%d\n%d ", n, odd[0]);
		for (auto i : eve) printf("%d ", i);
		printf("%d ", odd[1]);
	}
	else if (odd.size() == 1)
	{
		printf("%d ", odd[0]);
		for (auto i : eve) printf("%d ", i);
		puts("");
		odd[0]++, eve[eve.size() - 1]--;
		printf("%d\n", n);
		printf("%d ", odd[0]);
		for (auto i : eve) printf("%d ", i);
	}
	else
	{
		for (auto i : eve) printf("%d ", i);
		eve[0]++, eve[eve.size() - 1]--;
		printf("\n%d\n", n);
		for (auto i : eve) printf("%d ", i);
	}
}

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
const int INF = 1001001001;
const int MOD = 1000000007;

template <typename T>
void print(const T &v);

const int MAX = 510'000;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit()
{
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++)
    {
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

long long 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;
}

vector<pair<ll, ll>>
factorization(ll num)
{
    map<ll, ll> mp;

    ll tmp = num;
    for (ll i = 2; i * i <= num; i++)
    {
        while (tmp % i == 0)
        {
            mp[i]++;
            tmp /= i;
        }
    }
    if (tmp != 1)
    {
        mp[num]++;
    }
    vector<pair<ll, ll>> ret;
    for (auto m : mp)
    {
        ret.push_back(make_pair(m.first, m.second));
    }
    return ret;
}

int main()
{
    COMinit();
    int n, m;
    cin >> n >> m;

    auto fac = factorization(m);
    ll ans = 1;
    for (int i = 0; i < fac.size(); i++)
    {
        int tmp = fac[i].second;
        ans = (ans * COM(n + tmp - 1, tmp)) % MOD;
    }
    cout << ans << endl;
    return 0;
}

// Use For Debug
template <typename T>
void print(T const &v)
{
    for (int i = 0; i < v.size(); i++)
    {
        if (i)
            cout << " ";
        cout << v[i];
    }
    cout << endl;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<cstdlib>
#include<queue>
#include<set>
#include<cstdio>

using namespace std;

#define ll long long
#define rep(i, n) for(int i = 0; i < n; i++)
#define P pair<int, int>

typedef vector<int> vec;
typedef vector<vec> mat;

const ll mod = 1000000007;

deque<int> col;

int main(){
    int n;
    cin >> n;
    int a[n];
    rep(i, n) cin >> a[i];
    col.push_front(a[0]);
    for (int i = 1; i < n; i++){
        int idx = lower_bound(col.begin(), col.end(), a[i]) - col.begin();
        if(idx == 0){
            col.push_front(a[i]);
        }else{
            col[idx-1] = a[i];
        }
    }
    int ans = col.size();
    cout << ans << endl;
}

#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

int main(void){
	int n, m, t, i, j;
	scanf("%d %d", &n, &m);

	vector<int> sports;
	vector<int> votes(m, 0);

	for(i = 0;i < n;++i){
		scanf("%d", &t);
		sports.push_back(t);
	}

	for(i = 0;i < m;++i){
		scanf("%d", &t);
		for(j = 0;j < n;++j){
			if(sports[j] <= t){
				votes[j]++;
				break;
			}
		}
	}

	vector<int>::iterator itr = max_element(votes.begin(), votes.end());
	size_t d = distance(votes.begin(), itr);
	printf("%zu\n", d+1);

	return 0;
}


#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <vector>
using namespace std;
typedef long long ll;

int main() {
  string S;
  cin >> S;
  bool hflag = false, iflag = false;
  string ans = "Yes";
  for (int i = 0; i < S.length(); i++) {
    if (S[i] == 'h') {
      if ((i < S.length() - 1) && S[i + 1] == 'i') {
        i++;
        continue;
      } else {
        ans = "No";
        break;
      }
    } else {
      ans = "No";
      break;
    }
  }
  cout << ans << endl;
  return 0;
}

#include <bits/stdc++.h>//復習必須
#include<iostream>
#include<vector>
#include <cmath>
#include <map>
#include <algorithm>
#include <string>
#define rep(i, n) for (int i = 0; i < n; ++i)
using ll = long long;
using namespace std;
#define P pair<int, int>
int main () {
   string s ;
   cin >> s ;
   size_t n = s.length() ;
   bool flag = true ;
   if(n % 2 != 0 ){
       cout << "No" << endl;
       return 0 ;
   }else{

       rep(i , n /2){
           if(s[2*i] != 'h' || s[2*i + 1] != 'i'){
               flag = false ;

           }
       }
   }
   if(flag == true){
       cout << "Yes" << endl;
   }else{
       cout << "No" << endl;
   }
    return 0 ;
}


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

int main(){
  int n,m,q;
  cin>>n>>m>>q;
  vector<vector<int>> d(n,vector<int>(n));
  rep(i,m){
    int l,r;
    cin>>l>>r;
    l--; r--;
    d[n-l-1][r]++;
  }

  rep(i,n)for(int j=1;j<n;j++){
    d[i][j]+=d[i][j-1];
    if(i){
      if(d[i-1][j-1]!=d[i-1][j]){
        d[i][j]+=d[i-1][j]-d[i-1][j-1];
      }
    }
  }

  rep(i,q){
    int p,q;
    cin>>p>>q;
    p--; q--;
    cout<<d[n-p-1][q]<<endl;
  }
}

#include<bits/stdc++.h>
using namespace std;
int n, l, q;
vector<int>v;
vector<vector<int> >moves;
void preprocess(){
    int cur = 1;
    for(int i = 1; i <= n; i++){
        while(cur <= n && v[cur] - v[i] <= l){
            cur++;
        }
        moves[i][0] = cur - 1;
    }
    for(int j = 1; j <= 17; j++){
        for(int i = 1; i <= n; i++){
            int mid = moves[i][j - 1];
            if(mid != -1){
                moves[i][j] = moves[mid][j - 1];
            }
        }
    }
}
int query(int l, int r){
    int ans = 0;
    if(l > r){
        swap(l, r);
    }
    for(int i = 17; i >= 0; i--){
        if(moves[l][i] == -1){
            continue;
        }
        if(moves[l][i] < r){
            l = moves[l][i];
            ans += 1 << i;
        }
    }
    ans++;
    return ans;
}
int main(){
    cin >> n;
    v.assign(n + 2, 0);
    moves.assign(n + 2, vector<int>(19, -1));
    for(int i = 1; i <= n; i++){
        cin >> v[i];
    }
    cin >> l >> q;
    preprocess();
    for(int i = 1; i <= q; i++){
        int l, r;
        cin >> l >> r;
        cout << query(l, r) << '\n';
    }
    return 0;
}


// #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <locale>
#include <cctype>
#include <sstream>
using namespace std;

typedef long long LL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef map<int, int> MAPII;
typedef vector<pair<int, int> > VPII;
typedef multimap<int, string, greater<int> > MuMIS;

#define MP make_pair
#define fastIO	cin.tie(0); ios::sync_with_stdio(false);
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
//for gcc (未test)
// #define FOREACH_IT(it,c)	for(typeof(c)::iterator it=(c).begin(); it!=(c).end(); ++it)
//for Visual Studio
#define foreach_it(type,it,c) for(type::iterator it=c.begin(), c_end=c.end(); it!=c_end; ++it)

// ------------------- include, typedef, define END. -------------------

int Hit(int *rui){
	rui[0]++;
	// 塁を進める
	FOR(i, 1, 4){
		if (rui[i - 1]==2){
			rui[i]++;
			rui[i - 1] = 1;
		}
	}
	if (rui[3]!=0){
		rui[3] = 0;
		return 1;
	}
	return 0;
}

int Homerun(int *rui){
	int ret = 1;
	FOR(i, 0, 4)
		if (rui[i])
			ret++;
	return ret;
}

int main(){
	fastIO;
	int n, outCount = 0, tokuten = 0;
	string in;
	// rui[0]〜rui[2] = 1塁〜3塁, rui[3] = 本塁
	// 各値はその塁にいる人数(0〜2)
	int rui[4] = {};
	cin >> n;
	while (cin >> in){
		if (in == "OUT")
			outCount++;
		if (outCount < 3){
			if (in == "HIT"){
				tokuten += Hit(rui);
			}
			else if (in == "HOMERUN"){
				tokuten += Homerun(rui);
				FOR(i, 0, 4)	rui[i] = 0;
			}
		}
		else{
			cout << tokuten << endl;
			FOR(i, 0, 4)	rui[i] = 0;
			tokuten = 0;
			outCount = 0;
		}
	}
	return 0;
}

#include <iostream>
#include <string>

class Baseball{
private:
	int point;
	int out_count;
	int runner;
public:
	Baseball();
	void singleHit();
	void homerun();
	void out();
	void new_inning();
	int get_out_count();
	int get_point();
	~Baseball() = default;
};

Baseball::Baseball(){
	new_inning();
}

void Baseball::singleHit(){
	if(runner < 3){
		++runner;
	}
	else if(runner == 3){
		++point;
	}
}

void Baseball::homerun(){
	point += runner + 1;
	runner = 0;

}

void Baseball::out(){
	++out_count;
}

void Baseball::new_inning(){
	point = 0;
	out_count = 0;
	runner = 0;
}

int Baseball::get_out_count(){
	return out_count;
}

int Baseball::get_point(){
	return point;
}

int main(){
	int num;
	std::cin >> num; //data set number
	Baseball baseball;
	std::string event;

	for(int i=0; i<num; ++i){
		baseball.new_inning();

		while(baseball.get_out_count() < 3){
			std::cin >> event;

			if(event == "HIT"){
				baseball.singleHit();
			}
			else if(event == "HOMERUN"){
				baseball.homerun();
			}
			else if(event == "OUT"){
				baseball.out();
			}
		}
		//output
		std::cout << baseball.get_point() << std::endl;
	}

}


  #include <iostream>
#include <string>
using namespace std;
int main(){
	string str;
	int i,j;
	cin >> str;
	string st="";
	for( i=str.size()-1; i>=0 ; i-- )
		st+=str[i] ;
	cout << st << endl;
}

#include<iostream>
#include<string>
#include<algorithm>
#include<iterator>

int main(){
	std::string str;

	std::cin >> str;

	std::reverse_copy(str.begin(), str.end(),
		std::ostream_iterator<char>(std::cout,""));
  	std::cout << std::endl;
  	return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main(int argc, const char *argv[]) {
  vector<string> vs(3);
  for (int i = 0; i < 3; ++i) {
    cin >> vs[i];
  }

  vector<int> cur(3, 0);
  int t = 0;
  char ans;
  while (true) {
    if (cur[t] >= vs[t].size()) {
      ans = 'A' + t;
      break;
    }

    cur[t]++;
    t = vs[t][cur[t] - 1] - 'a';
  }

  cout << ans << '\n';
}

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

int main() {
  string s;
  cin >> s;
  if(s.size()==3){
	for(int i=2;i>=0;i--){
      cout << s.at(i);
    }
    cout << endl;
  }
  else{
    cout << s << endl;
  }
}


#include <iostream>

void ArrayDump(int *A, int N)
{
    for (int i = 0; i < N; i++) {
        std::cout << *(A + i);
        if (i != N - 1) {
            std::cout << " ";
        }
    }
    std::cout << std::endl;
}

int BubbleSort(int *A, int N)
{
    bool flag = true;
    int exchange_num = 0;
    while (flag) {
        flag = false;
        for (int j = N-1; j > 0; j--) {
            if (A[j] < A[j-1]) {
                int tmp = A[j];
                A[j] = A[j-1];
                A[j-1] = tmp;
                flag = true;
                exchange_num++;
            }
        }
    }
    return exchange_num;
}

int main(int argc, char* argv[])
{
    int array_size = 0;
    int array[100];

    std::cin >> array_size;
    for (int i = 0; i < array_size; i++) {
        std::cin >> array[i];
    }

    int exchange_num = BubbleSort(array, array_size);
    ArrayDump(array, array_size);
    std::cout << exchange_num << std::endl;
}

#define _USE_MATH_DEFINES
#include "bits/stdc++.h"
using namespace std;

//#define int long long
#define DBG 1
#define dump(o) if(DBG){cerr<<#o<<" "<<o<<endl;}
#define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define each(it,c) for(auto it=(c).begin();it!=(c).end();it++)
#define all(c) c.begin(),c.end()
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9 + 7);

signed main() {
	int n; cin >> n; vector<int>v(n);
	rep(i, 0, n)cin >> v[i];
	rep(i, 1, *min_element(all(v))) {
		bool f(true);
		rep(j, 0, n)if (v[j] % i != 0) {
			f = false;
			break;
		}
		if (f)cout << i << endl;
	}
	return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#define MOD 998244353
using namespace std;
typedef long long ll;

template <typename Tp> inline void getint(Tp &num){
	register int ch, neg = 0;
	while(!isdigit(ch = getchar())) if(ch == '-') neg = 1;
	num = ch & 15;
	while(isdigit(ch = getchar())) num = num * 10 + (ch & 15);
	if(neg) num = -num;
}

inline int fastpow(int bas, int ex){
	register int res = 1;
	for(; ex; ex >>= 1, bas = bas * (ll)bas % MOD) if(ex & 1) res = res * (ll)bas % MOD;
	return res;
}

inline int kazu(int a, const int &b) {return (a += b) >= MOD ? a - MOD : a;}
inline int hiku(int a, const int &b) {return (a -= b) < 0 ? a + MOD : a;}

int N, sum = 0, f[90005], g[90005];

int main(){
	getint(N), f[0] = g[0] = 1;
	for(register int i = 1, a; i <= N; i++){
		getint(a), sum += a;
		for(register int j = sum; j >= 0; j--){
			f[j] = f[j] * 2LL % MOD;
			if(j >= a) f[j] = kazu(f[j], f[j - a]), g[j] = kazu(g[j], g[j - a]);
		}
	}
	int ans = fastpow(3, N);
	for(register int i = sum + 1 >> 1; i <= sum; i++) ans = hiku(ans, f[i] * 3LL % MOD);
	if(!(sum & 1)) ans = kazu(ans, g[sum >> 1] * 3LL % MOD);
	return printf("%d\n", ans), 0;
}

#include <cassert>
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
/*
//#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
*/

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
// #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

const ll mod = 998244353;

const int N = 303;
const int M = 90003;
ll dp[N][M][2][2];

ll mod_pow(ll x, ll n){
    ll ret = 1;
    while(n){
        if(n&1) (ret *= x) %= mod;
        (x *= x) %= mod;
        n >>= 1;
    }
    return ret;
}

ll mod_inv(ll x){
    return mod_pow(x,mod-2);
}

const ll DIV = mod_inv(2);
int main(){
    int n;
    cin >>n;
    vector<int> a(n);
    int sa = 0;
    rep(i,n){
        cin >>a[i];
        sa += a[i];
    }

    dp[0][0][0][0] = 1;
    rep(i,n)rep(j,M)rep(x,2)rep(y,2)if(dp[i][j][x][y]){
        int nx = j+a[i];
        if(nx < M) (dp[i+1][nx][x][y] += dp[i][j][x][y]) %= mod;

        (dp[i+1][j][x|1][y] += dp[i][j][x][y]) %= mod;
        (dp[i+1][j][x][y|1] += dp[i][j][x][y]) %= mod;
    }

    ll sub = 0;
    rep(i,M)rep(x,2)rep(y,2){
        if(sa-i <= i){
            if(sa-i==i && (x==0 || y==0)) sub += dp[n][i][x][y]*DIV;
            else sub += dp[n][i][x][y];
            sub %= mod;
        }
    }
    sub *= 3;
    sub %= mod;

    ll ans = mod_pow(3,n) - sub + mod;
    ans %= mod;
    cout << ans << endl;
    return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 1000005
using namespace std;
typedef long long LL;
char s[N];
int dp[N][2];
int main()
{
	scanf("%s",s+1);
	dp[0][1]=1;
	for(int i=1;s[i];i++)
	{
		int d=s[i]-'0';
		dp[i][0]=min(dp[i-1][0]+d,dp[i-1][1]+10-d);
		dp[i][1]=min(dp[i-1][0]+d+1,dp[i-1][1]+9-d);
		if(d==9)dp[i][1]=dp[i-1][1];
	}
	printf("%d\n",dp[strlen(s+1)][0]);
	return 0;
}

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

//#define int long long
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define rep(i,n) for(int i=0;i<n;++i)
#define rep1(i,n) for(int i=1;i<n;++i)
#define exrep(i, a, b) for(ll i = a; i < b; i++)
#define out(x) cout << x << endl
#define EPS (1e-7)
#define gearup ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<pair<int,int> > vpii;
typedef vector<vector<int> > vvi;
typedef vector<vector<char> > vvc;
typedef vector<vector<bool> > vvb;
typedef vector<vector<double> > vvd;
typedef vector<vector<string> > vvs;
typedef vector<ll> vl;
typedef vector<vector<ll> > vvl;
typedef vector<vector<vector<ll> > > vvvl;
ll MOD = 1000000007;
const long long L_INF = 1LL << 60;
const int INF = 2147483647; // 2^31-1
const double PI = acos(-1);
//cout<<fixed<<setprecision(10);

template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b;return true;}return false;}
template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b;return true;}return false;}
template<class T> void debug(T v){rep(i,v.size()) cout<<v[i]<<" ";cout<<endl;}
const ll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

bool is_Prime(int x){
  if(x < 2)return false;
  else if(x == 2) return true;
  for(ll i = 2; i*i <= x; i++) if(x%i == 0) return false;
  return true;
}
vl res;
vl prime;
ll n;

signed main()
{
  gearup;
  cin >> n;
  //素数格納
  for(int i=2;i<=55555;i++){
    if(is_Prime(i) && (i % 5) == 1)prime.push_back(i);
  }
  rep(i,n){
    if(i)cout << " ";
    cout << prime[i];
  }
  cout << endl;
}


#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main(){
    string s;
    int n;
    int c_pos;
    cin>>n;
    cin.ignore();
    while(n--){
        getline(cin,s);
        while((c_pos=s.find("Hoshino"))!=string::npos){
            s.replace(c_pos,7,"Hoshina");
        }
        cout<<s<<endl;
    }
}

#include <iostream>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <complex>
#include <cstdio>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

string s;

int main(){
	getline(cin,s);
	while(getline(cin,s)){
		int a=s.find("Hoshino");
		while(a!=string::npos){
			s=s.substr(0,a)+"Hoshina"+s.substr(a+7);
			a=s.find("Hoshino");
		}
		cout<<s<<endl;
	}
}


#include <algorithm>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <tuple>
#include <vector>
using namespace std;
typedef long long ll;
ll const INF = 1LL << 60;

int main() {
  ll N;
  cin >> N;
  vector<ll> A(N);
  for (int i = 0; i < N; i++) {
    cin >> A[i];
  }
  vector<vector<ll>> memo(N + 1, vector<ll>(2));
  memo[0][0] = 0;
  memo[0][1] = -INF;
  for (int i = 0; i < N; i++) {
    memo[i + 1][0] = max(memo[i][0] + A[i], memo[i][1] - A[i]);
    memo[i + 1][1] = max(memo[i][0] - A[i], memo[i][1] + A[i]);
  }
  cout << memo[N][0] << endl;
  return 0;
}

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define repr(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define invrepr(i,a,b) for(int i=b-1;i>=a;i--)
#define invrep(i,n) invrepr(i,0,n)
#define repitr(itr,a) for(auto itr=a.begin();itr!=a.end();++itr)
#define P pair<int,int>
const int MOD=998244353;
const ll INF=2e15;
const double PI=acos(-1);

vector<P> vectorCnt(vector<int> a) {
    sort(a.begin(),a.end());
    int n=a.size();
    vector<pair<int,int>> b;
    int cnt=1;
    rep(i,n-1) {
        if (a[i+1]!=a[i]) {
            b.push_back({cnt,a[i]});
            cnt=1;
        } else {
            ++cnt;
        }
    }
    b.push_back({cnt,a[n-1]});
    return b;
}

int main() {
    ios_base::sync_with_stdio(false);

    int n;
    cin >> n;
    vector<ll> a(n);
    int cnt=0;
    rep(i,n) {
        cin >> a[i];
        if (a[i]<0) {
            ++cnt;
            a[i]=-a[i];
        }
    }
    sort(a.begin(),a.end());
    ll ans=0;
    rep(i,n) ans+=a[i];
    if (cnt%2==1) ans-=2*a[0];
    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair

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

int main() {
    int n;

    while(cin >> n && n) {
        int a = 0,b = 0;
        rep(i,n) {
            int x,y;
            cin >> x >> y;

            if(x == y) {
                a += x;
                b += y;
            } else if(x > y) {
                a += (x+y);
            } else {
                b += (x+y);
            }
        }

        cout << a << " " << b << endl;
    }

    return 0;
}

#include <iostream>
using namespace std;

int main()
{
	int n, a, b, count = 0, pointX = 0, pointY = 0;
	cin >> n;
	do {
		cin >> a >> b;
		if (a > b) {
			pointX += (a + b);
		}
		else if (a < b) {
			pointY += (a + b);
		}
		else {
			pointX += a;
			pointY += b;
		}
		count++;
		if (count == n) {
			cout << pointX << " " << pointY << endl;
			pointX = pointY = count = 0;
			cin >> n;
		}
	} while (n != 0);
	return 0;
}


//Author:xht37
#include <bits/stdc++.h>

#define ui unsigned int
#define ll long long
#define ul unsigned ll
#define ld long double

#define pi pair <int, int>
#define fi first
#define se second
#define mp make_pair

#define ls (p << 1)
#define rs (ls | 1)
#define md ((t[p].l + t[p].r) >> 1)

#define vi vector <int>
#define pb push_back
#define pq priority_queue

#define dbg(x) cerr << #x" = " << x << endl
#define debug(...) fprintf(stderr, __VA_ARGS__)

#define fl(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)

using namespace std;

namespace io {
	const int SI = 1 << 21 | 1;
	char IB[SI], *IS, *IT, OB[SI], *OS = OB, *OT = OS + SI - 1, c, ch[100];
	int f, t;
	#define gc() (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)
	inline void flush() {
		fwrite(OB, 1, OS - OB, stdout), OS = OB;
	}
	inline void pc(char x) {
		*OS++ = x;
		if (OS == OT) flush();
	}

	template <class I>
	inline void rd(I &x) {
		for (f = 1, c = gc(); c < '0' || c > '9'; c = gc()) if (c == '-') f = -1;
		for (x = 0; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + (c & 15), c = gc());
		x *= f;
	}
	template <class I>
	inline void rd(I &x, I &y) {
		rd(x), rd(y);
	}
	template <class I>
	inline void rd(I &x, I &y, I &z) {
		rd(x), rd(y), rd(z);
	}
	template <class I>
	inline void rda(I *a, int n) {
		for (int i = 1; i <= n; i++) rd(a[i]);
	}
	inline void rdc(char &c) {
		for (c = gc(); c < 33 || c > 126; c = gc());
	}
	inline void rds(char *s, int &n) {
		for (c = gc(); c < 33 || c > 126; c = gc());
		for (n = 0; c >= 33 && c <= 126; s[++n] = c, c = gc());
		s[n+1] = '\0';
	}
	inline void rds(string &s) {
		for (c = gc(); c < 33 || c > 126; c = gc());
		for (s.clear(); c >= 33 && c <= 126; s.pb(c), c = gc());
	}

	template <class I>
	inline void print(I x, char k = '\n') {
		if (!x) pc('0');
		if (x < 0) pc('-'), x = -x;
		while (x) ch[++t] = x % 10 + '0', x /= 10;
		while (t) pc(ch[t--]);
		pc(k);
	}
	template <class I>
	inline void print(I x, I y) {
		print(x, ' '), print(y);
	}
	template <class I>
	inline void print(I x, I y, I z) {
		print(x, ' '), print(y, ' '), print(z);
	}
	template <class I>
	inline void printa(I *a, int n) {
		for (int i = 1; i <= n; i++) print(a[i], " \n"[i==n]);
	}
	inline void printc(char c) {
		pc(c);
	}
	inline void prints(char *s, int n) {
		for (int i = 1; i <= n; i++) pc(s[i]);
		pc('\n');
	}
	inline void prints(string s) {
		int n = s.length();
		while (t < n) pc(s[t++]);
		pc('\n'), t = 0;
	}
	struct Flush {
		~Flush() {
			flush();
		}
	} flusher;
}
using io::rd;
using io::rda;
using io::rdc;
using io::rds;
using io::print;
using io::printa;
using io::printc;
using io::prints;

const int N = 1e5 + 7;
int n, x, p[N];
ll b[N], l[N], r[N], s[N], sum;

inline ll calc(int x, ll t) {
	return t <= b[x] ? t * l[x] : b[x] * l[x] + (t - b[x]) * r[x];
}

inline ll pd(ll t) {
	int w = t % x ? t % x : x, c = (t - w) / x;
	ll sum = 0, ret = 0;
	for (int i = 1; i <= c; i++) sum += s[p[i]];
	for (int i = c + 1; i <= n; i++)
		ret = max(ret, sum + calc(p[i], w));
	sum += s[p[c+1]];
	for (int i = 1; i <= c; i++)
		ret = max(ret, sum - s[p[i]] + calc(p[i], w));
	return ret;
}

int main() {
	rd(n, x);
	for (int i = 1; i <= n; i++)
		rd(b[i], l[i], r[i]), p[i] = i,
		s[i] = b[i] * l[i] + (x - b[i]) * r[i], sum += b[i] * l[i];
	sort(p + 1, p + n + 1, [&](int i, int j) { return s[i] > s[j]; });
	if (!sum) return print(0), 0;
	ll l = 1, r = 1ll * n * x;
	while (l < r) {
		ll mid = (l + r) >> 1;
		if (pd(mid) >= sum) r = mid;
		else l = mid + 1;
	}
	print(l);
	return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long int ll;
pair<ll,int> p[100005];
int main(){
	ll n,x; cin >> n >> x;
	vector<ll> b(n),l(n),u(n);
	for(int i=0;i<n;i++){
		cin >> b[i] >> l[i] >> u[i];
	}
	ll sum=0;
	for(int i=0;i<n;i++){
		p[i]=pair<ll,int>((x-b[i])*u[i]+b[i]*l[i],i);
		sum-=b[i]*l[i];
	}
	sort(p,p+n);
	ll ret=0;//満点を取る教科を数える
	int last=0;
	for(int i=n-1;i>=0;i--){
		if(sum+p[i].first>=0){
			ret+=(ll)(n-i-1)*(ll)x;//満点を取る教科はn-i-1個である
			last=i+1;
			break;
		}
		sum+=p[i].first;
	}
	ll Min=x;//中途半端に解く科目の得点の最小値
	sum=-sum;
	for(int i=0;i<last;i++){
		int v=p[i].second;
		Min=min(Min,(sum+l[v]-1)/l[v]);//中途半端に解く科目に最小の重みをつけた場合
		ll nsum=sum+b[v]*(u[v]-l[v]);//最大の重みをつける場合には更にディスアドバンテージが広がる
		Min=min(Min,(nsum+u[v]-1)/u[v]);
	}
	//貪欲に見ると満点を取る科目になる科目のうち中途半端に解くものを探索する場合、
	//満点を取る科目としてi=last-1も追加される
	for(int i=last;i<n;i++){
		int v=p[i].second;
		ll nsum=sum+p[i].first-p[last-1].first;
		Min=min(Min,(nsum+l[v]-1)/l[v]);
		ll nsum2=nsum+b[v]*(u[v]-l[v]);
		Min=min(Min,(nsum2+u[v]-1)/u[v]);
	}
	cout << ret+Min << 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 INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define yn(ans) if(ans)printf("Yes\n");else printf("No\n")
#define YN(ans) if(ans)printf("YES\n");else printf("NO\n")
#define vector1d(type,name,...) vector<type>name(__VA_ARGS__)
#define vector2d(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#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...);}
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
ll updivide(ll a,ll b){if(a%b==0) return a/b;else return (a/b)+1;}

int main(){
    INT(h,w);
    vector2d(int,table,h,w);
    vector<tuple<int,int,int,int>> ope;
    in(table);
    rep(y,h){
        rep(x,w){
            table[y][x]%=2;
            if(y<h-1&&table[y][x]==1){
                table[y+1][x]++;
                ope.push_back(make_tuple(y+1,x+1,y+2,x+1));
            }
            if(y==h-1&&x+1<w&&table[y][x]==1){
                table[y][x+1]++;
                ope.push_back(make_tuple(y+1,x+1,y+1,x+2));
            }
        }
    }
    out(ope.size());
    rep(i,ope.size())out(get<0>(ope[i]),get<1>(ope[i]),get<2>(ope[i]),get<3>(ope[i]));
}

#include<stdio.h>
#include<string.h>
#define N 8

int mp[N][N],row[N],col[N],dneg[2*N-1],dops[2*N-1];

void init()
{
    for(int i=0; i<N; i++)
        row[i]=col[i]=0;
    for(int i=0; i<2*N-1; i++)
        dneg[i]=dops[i]=0;
    for(int i=0; i<N; i++)
        for(int j=0; j<N; j++)
            mp[i][j]=0;
}

void check()
{
    for(int i=0; i<N; i++)
        for(int j=0; j<N; j++)
            if(mp[i][j])
            {
                if(row[i]!=j)
                    return ;
            }
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<N; j++)
        {
            printf("%c",(row[i]==j)?'Q':'.');
        }
        printf("\n");
    }
    return ;
}

void dfs(int i)
{
    if(i==N)
    {
        check();
        return ;
    }
    for(int j=0; j<N; j++)
    {
        if(col[j] || dops[i+j] || dneg[i-j+N-1]) continue;
        row[i]=j;
        col[j]=dops[i+j]=dneg[i-j+N-1]=1;
        dfs(i+1);
        row[i]=col[j]=dops[i+j]=dneg[i-j+N-1]=0;
    }
}

int main()
{
    int k,r,c;
    while(~scanf("%d",&k))
    {
        init();
        for(int i=0; i<k; i++)
        {
            scanf("%d%d",&r,&c);
            mp[r][c]=1;
        }
        dfs(0);
    }
    return 0;
}


#define	_USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <functional>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cfloat>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <string>
#include <set>
using namespace std;
int main(){

	int n;
	int a,b,c,d;
	cin>>n;
	vector<int> sum(n+1,0);
	vector<int> rank(n+1);
	sum[0]=-999999;
	for(int i=0;i<n*(n-1)/2;i++){
		cin>>a>>b>>c>>d;
		if(c>d){
			sum[a]+=3;
		}
		else if(c<d)
			sum[b]+=3;
		else{
			sum[a]++;
			sum[b]++;
		}
	}
	int k=0;
	int o=0;
	for(int i=0;i<n;i++){
		vector<int>::iterator it=find(sum.begin(),sum.end(),*max_element(sum.begin(),sum.end()));
		int j=it-sum.begin();
		if(k==0){
			k=1;
			o=sum[j];
			rank[j]=1;
		}
		else if(o==sum[j]){
			rank[j]=k;
		}
		else{
			k=i+1;
			o=sum[j];
			rank[j]=k;
		}
		sum[j]=-999999;
	}

	for(int i=1;i<=n;i++)
		cout<<rank[i]<<endl;

}


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

using ll = long long;
using ld  = long double;
using pint = pair<int, int>;
using pll = pair<ll, ll>;
using pld = pair<ld, ld>;
const int INF=1e9+7;
const ll LINF=9223372036854775807;
const ll MOD=1e9+7;
const ld PI=acos(-1);
const ld EPS = 1e-10; //微調整用（EPSより小さいと0と判定など）

int ii() { int x; if (scanf("%d", &x)==1) return x; else return 0; }
long long il() { long long x; if (scanf("%lld", &x)==1) return x; else return 0; }
string is() { string x; cin >> x; return x; }
char ic() { char x; cin >> x; return x; }
void oi(int x) { printf("%d ", x); }
void ol(long long x) { printf("%lld ", x); }
void od_nosp(double x) { printf("%.15f", x); } // 古い問題用
void od(double x) { printf("%.15f ", x); }
// long doubleで受け取り、fをLfなどに変えて出力すると、変な数値が出る
// それをなんとかするには独自の出力を作らなければならなそう
void os(const string &s) { printf("%s ", s.c_str()); }
void oc(const char &c) { printf("%c ", c); }
#define o_map(v){cerr << #v << endl; for(const auto& xxx: v){cout << xxx.first << " " << xxx.second << "\n";}} //動作未確認
void br() { putchar('\n'); }

// #define gcd __gcd //llは受け取らない C++17~のgcdと違うので注意
// int lcm(int a, int b){return a / gcd(a, b) * b;}
#define begin_end(a) a.begin(),a.end() //sort(begin_end(vec));
#define REP(i,m,n) for(ll i=(ll)(m) ; i < (ll)(n) ; i++ )
#define DREP(i,m,n) for(ll i=(ll)(m) ; i > (ll)(n) ; i-- )
#define rep(i,n) REP(i,0,n)
#define m_p(a,b) make_pair(a,b)
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define p_b push_back
#define SZ(x) ((int)(x).size) //size()がunsignedなのでエラー避けに

// coutによるpairの出力（空白区切り）
template<typename T1, typename T2> ostream& operator<<(ostream& s, const pair<T1, T2>& p) {return s << "(" << p.first << " " << p.second << ")";}
// coutによるvectorの出力（空白区切り）
template<typename T> ostream& operator<<(ostream& s, const vector<T>& v) {
  int len = v.size();
  for (int i = 0; i < len; ++i) {
    s << v[i]; if (i < len - 1) s << " "; //"\t"に変えるとTabで見やすく区切る
  }
  return s;
}
// coutによる多次元vectorの出力（空白区切り）
template<typename T> ostream& operator<<(ostream& s, const vector< vector<T> >& vv) {
  int len = vv.size();
  for (int i = 0; i < len; ++i) {
    s << vv[i] << endl;
  }
  return s;
}

//最大値、最小値の更新。更新したor等しければtrueを返す
template<typename T>
bool chmax(T& a, T b){return (a = max(a, b)) == b;}
template<typename T>
bool chmin(T& a, T b){return (a = min(a, b)) == b;}

//4近傍（上下左右） rep(i, 2) にすると右・下だけに進む
vector<int> dx_4 = {1, 0, -1, 0};
vector<int> dy_4 = {0, 1, 0, -1};

// -------- template end - //

// - library ------------- //

// --------- library end - //

int main(){

  ll n, m, d;
  cin >> n >> m >> d;

  ld ans;
  if (d==0){
    ans = ld(m-1) / n;
  }
  else if (n - d - d <= 0){
    ans = ld(m-1) / n; // d==0 のときと結果は同じ
  }
  else{
    // n-2d >= 1
    ans = ld((n-d-d)*2 + (d+d)) / n * (m-1) / n;
  }

  od_nosp(ans);

}

#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...);
}

#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

const long long INF = 1e18;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<long long> a(n + 1);
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];
    }
    vector<long long> dp1(n + 1, -INF), dp0(n + 1, -INF);

    dp0[1] = a[1];
    dp1[1] = -a[1];
    for (int i = 2; i < n; i++)
    {
        dp0[i] = max(dp0[i - 1] + a[i], dp1[i - 1] - a[i]);
        dp1[i] = max(dp0[i - 1] - a[i], dp1[i - 1] + a[i]);
    }
    long long ans = max(dp0[n - 1] + a[n], dp1[n - 1] - a[n]);
    cout << ans;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

#define MOD 1000000007
#define MOD2 998244353
#define int long long
#define double long double
#define EPS 1e-9
//#define PI 3.14159265358979

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

using namespace std;

template < typename T >
ostream &operator<<(ostream &os, const vector< T > &A) {
	for (int i = 0; i < A.size(); i++)
		os << A[i] << " ";
	os << endl;
	return os;
}
template <>
ostream &operator<<(ostream &os, const vector< vector< int > > &A) {
	int N = A.size();
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < A[i].size(); j++)
			os << A[i][j] << " ";
		os << endl;
	}
	return os;
}
template < typename T, typename U >
ostream &operator<<(ostream &os, const pair< T, U > &p) {
	os << "(" << p.first << "," << p.second << ")";
	return os;
}

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

struct edge {
	int from, to, d, c, i;
	edge(int _from = 0, int _to = 0, int _d = 0, int _c = 0) {
		from = _from;
		to = _to;
		d = _d;
		c = _c;
	}
	bool operator<(const edge &rhs) const {
		return (d == rhs.d) ? (c < rhs.c) : (d < rhs.d);
	}
};
struct aabb {
	int x1, y1, x2, y2;
	aabb(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
};

typedef vector< edge > edges;
typedef vector< edges > graph;
struct flow {
	int to, cap, rev, cost;
	flow(int to = 0, int cap = 0, int rev = 0, int cost = 0) : to(to), cap(cap), rev(rev), cost(cost) {}
};
typedef vector< vector< flow > > flows;

const int di[4] = {0, -1, 0, 1};
const int dj[4] = {-1, 0, 1, 0};
const int ci[5] = {0, 0, -1, 0, 1};
const int cj[5] = {0, -1, 0, 1, 0};
const ll LINF = LLONG_MAX / 2;
const int INF = INT_MAX / 2;
const double PI = acos(-1);

int pow2(int n) { return 1LL << n; }
template < typename T, typename U >
bool chmin(T &x, const U &y) {
	if (x > y) {
		x = y;
		return true;
	}
	return false;
}
template < typename T, typename U >
bool chmax(T &x, const U &y) {
	if (x < y) {
		x = y;
		return true;
	}
	return false;
}

template < typename A, size_t N, typename T >
void Fill(A (&array)[N], const T &val) {
	fill((T *)array, (T *)(array + N), val);
}
struct initializer {
	initializer() {
		cout << fixed << setprecision(20);
	}
};
initializer _____;
bool BMdfs(vector< int > &M, vector< vector< int > > &G, vector< bool > &used, int v) {
	used[v] = true;
	rep(i, G[v].size()) {
		int u = G[v][i], w = M[u];
		if (w < 0 || !used[w] && BMdfs(M, G, used, w)) {
			M[v] = u;
			M[u] = v;
			return true;
		}
	}
	return false;
}
int BMatching(vector< vector< int > > &G, vector< int > &M) {
	vector< bool > used(G.size());
	M.assign(G.size(), -1);
	int ret = 0;
	rep(v, G.size()) {
		if (M[v] < 0) {
			used.assign(G.size(), false);
			if (BMdfs(M, G, used, v)) {
				ret++;
			}
		}
	}
	return ret;
}
int BMatching(vector< vector< int > > &G) {
	vector< int > M;
	return BMatching(G, M);
}
int N, M, K, T, Q, H, W;
signed main() {
	cin >> N;
	vector< int > A(N);
	rep(i, N) cin >> A[i];
	vector< int > B(N);
	rep(i, N) cin >> B[i];
	int j = 0;
	rep(i, N) {
		if (A[i] == B[i]) {
			while (j < N && (A[i] == A[j] || A[i] == B[j]))
				j++;
			if (j == N) {
				cout << "No" << endl;
				return 0;
			}
			swap(B[i], B[j]);
		}
		if (i < N - 1 && A[i] != A[i + 1])
			j = 0;
	}
	cout << "Yes" << endl;
	cout << B;
	return 0;
}


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

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

  vector<int> R, G, B;
  rep(i,n) {
    if(s[i] == 'R') R.push_back(i);
    if(s[i] == 'G') G.push_back(i);
    if(s[i] == 'B') B.push_back(i);
  }

  long long ans = 0;
  for (auto r : R) {
    for (auto g : G) {
      int x = -1, y = -1, z = -1;
      int mi = min(r,g);
      int ma = max(r,g);
      if((r + g)%2 == 0) x = (r + g)/2;
      y = ma + abs(r - g);
      z = mi - abs(r - g);
      int add = B.size();
      if(binary_search(B.begin(),B.end(),x)) add--;
      if(binary_search(B.begin(),B.end(),y)) add--;
      if(binary_search(B.begin(),B.end(),z)) add--;
      ans += add;
    }
  }

  cout << ans << '\n';

}

#include<cstdio>
using namespace std;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
char s[400][401];
int par[160000];
int c1[160000];
int c2[160000];
int find(int x) {
    if (par[x] == 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;
    par[x] = y;
}
int main() {
    int h, w, i, j, k;
    long long ans = 0;
    scanf("%d %d", &h, &w);
    for (i = 0; i < h; i++) scanf("%s", s[i]);
    for (i = 0; i < h * w; i++) par[i] = i;
    for (i = 0; i < h; i++) {
        for (j = 0; j < w; j++) {
            for (k = 0; k < 4; k++) {
                int x = i + dx[k];
                int y = j + dy[k];
                if (x < 0 || x >= h || y < 0 || y >= w) continue;
                if (s[i][j] != s[x][y]) unite(i * w + j, x * w + y);
            }
        }
    }
    for (i = 0; i < h; i++) {
        for (j = 0; j < w; j++) {
            if (s[i][j] == '.') {
                c1[find(i * w + j)]++;
            } else {
                c2[find(i * w + j)]++;
            }
        }
    }
    for (i = 0; i < h * w; i++) ans += (long long)c1[i] * c2[i];
    printf("%lld\n", ans);
    return 0;
}


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

int main(){
	int n;
	int area[11][11];
	while(cin >> n){
		if(n == 0) break;
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){
				cin >> area[i][j];
			}
		}
		for(int i = 0; i < n; i++){
			int count = 0;
			for(int j = 0; j < n; j++){
				count += area[i][j];
			}
			area[i][n] = count;
		}
		for(int j = 0; j <= n; j++){
			int count = 0;
			for(int i = 0; i < n; i++){
				count += area[i][j];
			}
			area[n][j] = count;
		}
		for(int i = 0; i <= n; i++){
			for(int j = 0; j <= n; j++){
				cout << setw(5) << area[i][j];
			}
			cout << endl;
		}
	}
	return 0;
}

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

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,int> plli;
typedef pair<int,pii> pipii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<pii> vpii;

#define rep(i,n) for (int i=0;i<(n);i++)
#define rep2(i,a,b) for (int i=(a);i<(b);i++)
#define rrep(i,n) for (int i=(n);i>0;i--)
#define rrep2(i,a,b) for (int i=(a);i>b;i--)
#define pb push_back
#define fi first
#define se second
#define all(a) (a).begin(),(a).end()

const ll mod = 1e9 + 7;
const ll INF = 1<<30;
const int dx4[4] = {1, 0, -1, 0};
const int dy4[4] = {0, 1, 0, -1};
const int dx8[8] = {1, 1, 1, 0, 0, -1, -1, -1};
const int dy8[8] = {0, 1, -1, 1, -1, 0, 1, -1};
const double pi = 3.141592653589793;

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int a, b, c;
    cin >> a >> b >> c;
    while (a != 0) {
        int n;
        cin >> n;
        int ans[a + b + c + 1];
        fill(ans, ans + a + b + c, 2);
        int ii[n] = {}; int jj[n] = {}; int kk[n] = {}; int rr[n] = {};
        rep(m, n) {
            int i, j, k, r;
            cin >> i >> j >> k >> r;
            ii[m] = i; jj[m] = j; kk[m] = k; rr[m] = r;
            if (r == 1) {
                ans[i] = 1;
                ans[j] = 1;
                ans[k] = 1;
            }
            else {
                if (ans[i] == 1 && ans[j] == 1) ans[k] = 0;
                else if (ans[i] == 1 && ans[k] == 1) ans[j] = 0;
                else if (ans[j] == 1 && ans[k] == 1) ans[i] = 0;

            }

        }
        rep(m, n) {
            int i = ii[m]; int j = jj[m]; int k = kk[m]; int r = rr[m];
            if (r == 1) {
                ans[i] = 1;
                ans[j] = 1;
                ans[k] = 1;
            }
            else {
                if (ans[i] == 1 && ans[j] == 1) ans[k] = 0;
                else if (ans[i] == 1 && ans[k] == 1) ans[j] = 0;
                else if (ans[j] == 1 && ans[k] == 1) ans[i] = 0;

            }

        }
        rep2(i, 1, a + b + c + 1) cout << ans[i] << endl;
        cin >> a >> b >> c;
    }
}


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

/*------------------------------------------------------------------*/

#define ll long long int
#define mp make_pair
#define pb push_back
#define MOD 1000000007

bool isvowel(char c)
{
    if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
        return true;
        return false;
}
ll isprime(ll n)
{
    ll ans=1;
    for(ll i=2;i<=sqrt(n);i++)
    {
        if(n%i==0)
            ans = i;
    }
    return ans;
}
ll power(ll a,ll b,ll m)
{
    if(b==0)
        return 1;
    if(b==1)
        return a%m;
    ll temp=power(a,b/2,m);
    if(b%2==0)
        return ((temp%m)*(temp%m))%m;
    else
        return ((((temp%m)*(temp%m))%m)*a%m)%m;
}

/*-----------------------------------------------------------------------------*/

ll c(ll n, ll k)
{
    ll C[n + 1][k + 1];
    ll i, j;

    for (i = 0; i <= n; i++)
    {
        for (j = 0; j <= min(i, k); j++)
        {

            if (j == 0 || j == i)
                C[i][j] = 1;

            else
                C[i][j] = (C[i - 1][j - 1]%MOD +
                          C[i - 1][j])%MOD;
        }
    }
    return C[n][k]%MOD;
}
ll modInverse(ll a, ll m)
{
    ll m0 = m;
    ll y = 0, x = 1;

    if (m == 1)
      return 0;

    while (a > 1)
    {

        ll q = a / m;
        ll t = m;
        m = a % m, a = t;
        t = y;

        y = x - q * y;
        x = t;
    }
    if (x < 0)
       x += m0;

    return x;
}
int main()
{
    ios_base::sync_with_stdio(false);
	cin.tie(NULL);

    //freopen("1.txt","rt",stdin);
    //freopen("output.txt","wwt",stdout);

    ll t;
    t=1;
    //cin>>t;
    //ll t1=0;
    while(t--)
    {
       ll n,m;
       cin>>n>>m;
       ll p[m];
       string s[m];
       map<ll,ll>m1;
       ll ans1=0,ans2=0;
       for(ll i=0;i<m;i++)
       {
           cin>>p[i]>>s[i];
           if(s[i]=="AC")
           {
              if(m1[p[i]]!=-1)
              {
                  ans2+=m1[p[i]];
                  m1[p[i]]=-1;
                  ans1++;
              }
           }
           else
           {
               if(m1[p[i]]!=-1)
                 m1[p[i]]++;
           }
       }
       cout<<ans1<<" "<<ans2<<endl;
    }
}

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

typedef long long ll;
const int maxn = 2e5 + 10;
int n; ll k, ans, a[maxn], lef[maxn], rig[maxn];

int main() {
  scanf("%d %lld", &n, &k);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", a + i), ans += a[i];
  }
  ans += (n - 1) * k;
  lef[1] = a[1];
  for (int i = 2; i <= n; i++) {
    lef[i] = min(a[i], lef[i - 1] + k);
  }
  rig[n] = a[n];
  for (int i = n - 1; i; i--) {
    rig[i] = min(a[i], rig[i + 1] + k);
  }
  for (int i = 2; i < n; i++) {
    ans += min(lef[i], rig[i]);
  }
  printf("%lld", ans);
  return 0;
}


#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <typeinfo>
#include <map>

using namespace std;
typedef long long LL;
#define REP(i,N) for(int i = 0; i < (int)N; i++)
int dy[4] = {1,0,-1,0};
int dx[4] = {0,1,0,-1};
bool gems[25][25];
vector<bool> hantei;
int main(){
	int n;
	cin >> n;
	while(n!=0){
		REP(i,25)memset(gems[i],0,sizeof(gems[i]));
		REP(i,n){
			int x,y;
			cin >> x >> y;
			gems[x][y] = true;
		}
		int ret=0;
		int m;
		cin >> m;
		int nowx,nowy;
		nowx = nowy = 10;
		REP(i,m){
			char c;
			int nor;
			cin >> c >> nor;
			int dir;
			switch(c){
				case 'N':
					dir = 0;
					break;
				case 'E':
					dir = 1;
					break;
				case 'S':
					dir = 2;
					break;
				case 'W':
					dir = 3;
					break;
			}

			REP(j,nor){
				nowx += dx[dir];
				nowy += dy[dir];
				if(gems[nowx][nowy]){
					ret++;
					gems[nowx][nowy] = false;
				}
			}
		}
		if(ret == n){
			hantei.push_back(1);
		}else{
			hantei.push_back(0);
		}
		cin >> n;
	}
	REP(i,hantei.size()){
		string dis = hantei[i] ? "Yes":"No";
		cout << dis << endl;
	}
	return 0;
}

#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;
static const int MAX_N = 12;
int field[MAX_N][MAX_N];
static const int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };

int stoi(std::string str) {
	int ret;
	std::stringstream ss;
	ss << str;
	ss >> ret;
	return ret;
}

void dfs(int y, int x) {
	field[y][x] = 0;
	for (int i = 0; i < 4; i++) {
		if (0 <= x + dx[i] && x + dx[i] < 12 && 0 <= y + dy[i] && y + dy[i] < 12 && field[y + dy[i]][x + dx[i]] == 1) {
			dfs(y + dy[i], x + dx[i]);
		}
	}
}

void printTable() {
	cout << "------------------" << endl;
	for (int i = 0; i < 12; i++) {
		for (int j = 0; j < 12; j++) {
			cout << field[i][j];
		}
		cout << endl;
	}
}

int main()
{
	string s = "";

	while (cin >> s) {
		int cnt = 0;
		if (s == "")break;
		//input
		for (int i = 0; i < 12; i++)field[0][i] = s[i] - '0';// stoi(s[i]);
		for (int i = 1; i < 12; i++) {
			cin >> s;
			for (int j = 0; j < 12; j++) {
				field[i][j] = s[j] - '0';// stoi(s[j]);
			}
		}
		//printTable();
		for (int i = 0; i < 12; i++) {
			for (int j = 0; j < 12; j++) {
				if (field[i][j] == 1) {
					cnt++;
					dfs(i, j);
			//		printTable();
				}
			}
		}
		cout << cnt << endl;

	}

    return 0;
}


#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;

/* a と b の最大公約数を返す関数 */
long long GCD(long long a, long long b) {
	if (b == 0) return a;
	else return GCD(b, a % b);
}

int main()
{
	int N;
	string S;
	cin >> N >> S;

	vector<vector<int>> su(2, vector<int>((unsigned int)(N + 100), 0));

	su.at(0).at(0) = 0;
	su.at(1).at(0) = 0;
	for (int i = 0; i < N; ++i)
	{
		if (S.at(i) == 'W')
		{
			su.at(0).at(i + 1) = su.at(0).at(i) + 1;
			su.at(1).at(i + 1) = su.at(1).at(i);
		}
		else
		{
			su.at(0).at(i + 1) = su.at(0).at(i);
			su.at(1).at(i + 1) = su.at(1).at(i) + 1;
		}
	}

	int ret = (int)(3 * 1e5);
	int l_min;
	rep(i, N)
	{
		l_min = (su.at(0).at(i)) + (su.at(1).at(N) - su.at(1).at(i+1));
		ret = min(l_min, ret);
	}

	cout << ret << endl;

	return 0;
}

#include<iostream>
using namespace std;

int N,M,A[1001],B,V[1001];
int main(int i,int j){
	cin>>N>>M;
	for(;i<=N+M;i++){
		cin>>((i<=N)?A[i]:B);
		for(j=1;j<=N;j++){
			if(i>N&&B>=A[j]){
				V[j]++;break;
			}
		}
	}
	int max=0;
	for(i=1;i<=N;i++){
		if(max<V[i]){
			max=V[i];j=i;
		}
	}
	cout<<j<<endl;
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INPUT_SIZE  1024

void trace(int num, int* array);
int bubbleSort(int num, int* array);

int
main(int argc, char* argv[])
{
    char input[MAX_INPUT_SIZE];

    int num = atoi(fgets(input, sizeof(input), stdin));
    int* array = new int[num];

    atoi(fgets(input, sizeof(input), stdin));
    for (int i = 0; i < num; i++) {
        array[i] = i == 0 ?
            atoi(strtok(input, " ")) : atoi(strtok(NULL, " "));
        //printf("%d\n", array[i]);
    }

    printf("%d\n", bubbleSort(num, array));

    if (array != NULL) {
        delete [] array;
    }

    return 0;
}

void
trace(int num, int* array)
{
    for (int i = 0; i < num; i++) {
        if (i != 0) {
            printf(" ");
        }
        printf("%d", array[i]);
    }
    printf("\n");
}

int
bubbleSort(int num, int* array)
{
    int ret = 0, loopCount = 0;

    for (int j = 0; j < num; j++) {
        for (int i = num-1; i > 0; i--) {
            if (array[i] < array[i-1]) {
                int tmp = array[i];
                array[i] = array[i-1];
                array[i-1] = tmp;
                ret++;
            }
        }
    }
    /*
    for (int i = 0; i < num; i++) {
        printf("%d\n", array[i]);
    }
    */
    trace(num, array);

    return ret;
}

#include<iostream>
using namespace std;

int main()
{
	int flag = 1, tmp, n, a[100], count = 0;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	while (flag)
	{
		flag = 0;
		for (int i = n - 1; i > 0; i--)
			if (a[i] < a[i - 1])
			{
				tmp = a[i];
				a[i] = a[i - 1];
				a[i - 1] = tmp;
				count++;
				flag = 1;
			}
	}
	for (int i = 0; i < n; i++)
	{
		if (i)
			cout << " ";
		cout << a[i];
	}
	cout << endl << count << endl;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> P;
typedef tuple<long double,ll,ll> T;
const ll mod=1e9+7,INF=mod*mod*3;//M_PI
#define rep(i,N) for(ll i=0; i<(N); i++)
#define rep1(i,N) for(ll i=1; i<(N); i++)
#define f first
#define s second
#define pb push_back
#define mp make_pair

ll N,M,Q;
vector<ll> V[505];

int main(){

cin.tie(0);
ios::sync_with_stdio(false);

cin>>N>>M>>Q;
rep(i,M){
	ll L,R;
	cin>>L>>R;
	V[L].pb(R);
}
rep1(i,N+1){
	if(V[i].size()) sort(V[i].begin(),V[i].end());
}
rep(i,Q){
	ll ans=0;
	ll p,q;
	cin>>p>>q;
	for(ll j=p;j<=q;j++){
		ll sz=V[j].size();
		ll k=upper_bound(V[j].begin(),V[j].end(),q)-V[j].begin();
		ans+=k;
	}
	cout<<ans<<endl;
}

}

#include "bits/stdc++.h"
#define ll long long
#define lld long double
#define MOD 1000000007
#define inf 1000000007
#define pii pair<int,int>
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
// ll power(ll x,ll y, ll md=inf){ll res = 1;x%=md;while(y){if(y&1)res = (res*x)%md;x *= x; if(x>=md) x %= md; y >>= 1;}return res;}

using namespace std;

#define endl '\n'
// #define int ll

signed main() {
	fast;

	int h,w;
	cin>>h>>w;

	pii v[200002];
	for(int i=0;i<h;i++) cin>>v[i].f>>v[i].s;

	map<int,int> mp;
	for(int i=1;i<=w;i++) mp[i] = 0;

	map<int,int> mini = {{0,w}};

	for(int i=0;i<h;i++) {
		int r = v[i].s;

		auto it = mp.lower_bound(v[i].f);

		if(r==w) {
			while(it!=mp.end() && it->f <= r) {
				auto it1 = it++;
				auto it2 = mini.find(it1->s);
				if(it2->s==1) mini.erase(it2);
				else it2->s --;
				mp.erase(it1);
			}

			if(mini.size()==0) cout<<-1<<endl;
			else cout<<mini.begin()->f+i+1<<endl;
		}
		else {
			int mn = inf;

			while(it!=mp.end() && it->f <= r) {
				mn = min(mn, r+1-(it->f)+(it->s));
				auto it1 = it++;
				auto it2 = mini.find(it1->s);
				if(it2->s==1) mini.erase(it2);
				else it2->s --;
				mp.erase(it1);
			}

			if(mn<inf) {
				if(it!=mp.end() && it->f == r + 1) {
					if(it->s > mn) {
						auto it1 = mini.find(it->s);
						if(it1->s ==1) mini.erase(it1);
						else it1->s --;
						mini[mn]++;
						it->s = mn;
					}
				}
				else {
					mp.emplace_hint(it,r+1,mn);
					mini[mn]++;
				}
				cout<<mini.begin()->f+i+1<<endl;
			}
			else {
				if(mini.size()==0) cout<<-1<<endl;
				else cout<<mini.begin()->f+i+1<<endl;
			}

		}

	}
}


#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i=0; i<(int)(n); i++)
int main(){
int H, W, ans=1; cin >> H >> W; string A[H];
REP(i, H){ cin >> A[i]; }
int B[H][W]={}; vector< pair<int, int> > C;
REP(i, H){ REP(j, W){
  if(A[i][j]=='#'){  B[i][j]=1; C.push_back(make_pair(i, j)); }
} }
REP(i, H*W){
if((int)C.size()==H*W){ cout << ans-1 << "\n"; return 0; }
int a=C[i].first, b=C[i].second, c=B[a][b]+1;
if(a>0&&!B[a-1][b]){ B[a-1][b]=c; C.push_back(make_pair(a-1, b)); }
if(b>0&&!B[a][b-1]){ B[a][b-1]=c; C.push_back(make_pair(a, b-1)); }
if(a<H-1&&!B[a+1][b]){ B[a+1][b]=c; C.push_back(make_pair(a+1, b)); }
if(b<W-1&&!B[a][b+1]){ B[a][b+1]=c; C.push_back(make_pair(a, b+1)); }
ans=c;
}
}

#include <bits/stdc++.h>

using namespace std;
typedef pair<int,int> pii;
const int N = 1010;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int _w;

int n, m;
char str[N][N];
int dis[N][N];
queue<pii> q;

bool inside( int x, int y ) {
	return x >= 1 && x <= n && y >= 1 && y <= m;
}

int main() {
	_w = scanf( "%d%d", &n, &m );
	for( int i = 1; i <= n; ++i )
		_w = scanf( "%s", str[i]+1 );
	memset(dis, -1, sizeof dis);
	for( int i = 1; i <= n; ++i )
		for( int j = 1; j <= m; ++j )
			if( str[i][j] == '#' )
				dis[i][j] = 0, q.push( pii(i, j) );
	int ans = 0;
	while( !q.empty() ) {
		pii now = q.front(); q.pop();
		ans = max(ans, dis[now.first][now.second]);
		for( int i = 0; i < 4; ++i ) {
			int nx = now.first + dx[i];
			int ny = now.second + dy[i];
			if( inside(nx, ny) && dis[nx][ny] == -1 ) {
				dis[nx][ny] = dis[now.first][now.second] + 1;
				q.push( pii(nx, ny) );
			}
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;

ll modpow(ll a,ll n,ll mod){
  if(n == 0) return 1LL;
  if(n % 2 == 0){
    ll d = modpow(a,n/2,mod) % mod;
    return (d*d) % mod;
  }
  return (a % mod) * (modpow(a,n-1,mod) % mod) % mod;
}

int main(){
  ll n; cin >> n;
  vector<ll> a(n);
  for(int i = 0; i < n; i++) cin >> a[i];
  ll sum = 0;
  ll times = 0;
  while(times < 65){
    ll cnt1 = 0,cnt0 = 0;
    ll b_sum = 0;
    for(int i = 0; i < n; i++){
      if(a[i] % 2 == 1) cnt1++;
      a[i]/=2;
    }
    cnt0 = n-cnt1;
    b_sum = cnt0*cnt1%MOD;
    ll res = modpow(2,times,MOD)*b_sum;
    sum += res%MOD;
    sum %= MOD;
    times++;
  }
  cout << sum << endl;
  return 0;
}

#include <stdio.h>

#include <iostream>
#include <vector>
#include <array>

constexpr int64_t MOD = 1'000'000'007;
constexpr int64_t help = 1;

int main() {
	int64_t n;

	std::cin >> n;

	std::array<uint64_t, 62> bits{};
	for (int64_t i = 0; i < n; i++) {
		int64_t d;
		std::cin >> d;
		for (int64_t b = 0; b < 62; b++) {
			bits[b] += !!(d & (help << b));
		}
	}

	int64_t ans = 0;

	for (int64_t b = 0; b < 62; b++) {
		int64_t p = (help << b) % MOD;
		ans += (bits[b]*(n-bits[b]) % MOD) * p;
		ans %= MOD;
	}

	std::cout << ans;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define inf 1001001001
#define mod 1000000007
#define pi 3.141592653589793
typedef vector<int> vi;
typedef vector<ll> vl;
ll gcd(ll a,ll b){
    if(b>a) swap(a,b);
    if(b==0) return a;
    return gcd(b,a%b);
}
ll lcm(ll a,ll b){
    ll g=gcd(a,b);
    return a/g*b;
}
ll rep_jijo(ll n,ll x){
    if(x==0) return 1;
    if(x%2==0){
        ll t=rep_jijo(n,x/2);
        return t*t%mod;
    }
    return n*rep_jijo(n,x-1)%mod;
}
ll com(ll n,ll r){
    ll x=1,y=1;
    ll tmp=n;
    while(tmp>=n-r+1){
        x=x*tmp%mod;
        tmp--;
    }
    while(r>0){
        y=y*r%mod;
        r--;
    }
    return x*rep_jijo(y,mod-2)%mod;
}

int main (){
    int n;
    cin >> n;
    double mn=inf;
    double sum=0;
    int ans;
    vector<double>a(n);
    rep(i,n){
        double x;
        cin >> x;
        a[i]=x;
        sum+=x;
    }
    sum/=n;
    rep(i,n){
        double sub=abs(a[i]-sum);
        if(sub<mn) {
            mn=sub;
            ans=i;
        }
    }
    cout << ans << endl;
    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <iomanip>
#define _USE_MATH_DEFINES
#include <math.h>
#include <numeric>

//#include <map>

using namespace std;

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

	vector<int> vData;

	for (int i = 0; i < n; i++)
	{
		int t;
		cin >> t;
		vData.push_back(t);
	}

	reverse(vData.begin(), vData.end());

	for (int i = 0; i < vData.size(); i++)
	{
		cout << vData.at(i);
		if (i == vData.size() - 1)break;
		cout << " ";
	}
	cout << endl;

	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
    int N, T;
    cin >> N >> T;
    vector<int> A(N), B(N);
    for(int i = 0; i < N; i++) cin >> A[i] >> B[i];
    vector<int> ind(N);
    for(int i = 0; i < N; i++) ind[i] = i;
    sort(ind.begin(), ind.end(), [&](int i, int j){
        return A[i] < A[j];
    });
    vector<vector<int>> dp(N + 1, vector<int> (T + 1, 0));
    for(int k = 0; k < N; k++){
        int i = ind[k];
        for(int j = 0; j <= T; j++){
            dp[k + 1][j] = max(dp[k + 1][j], dp[k][j]);
            if(j == T) continue;
            if(j + A[i] > T) dp[k + 1][T] = max(dp[k + 1][T], dp[k][j] + B[i]);
            else dp[k + 1][j + A[i]] = max(dp[k + 1][j + A[i]], dp[k][j] + B[i]);
        }
    }
    cout << dp[N][T] << endl;
}

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

int qmin(int a, int b){
	return (a < b) ? a : b;
}
int qmax(int a, int b){
	return (a > b) ? a : b;
}

int n;
pair<int, int> seg[100100];

int len(int l, int r){
	return qmax(r-l+1, 0);
}

int main(){
	scanf("%d", &n);
	rep(i, n) scanf("%d%d", &seg[i].L, &seg[i].R);
	int lmax = seg[0].L, lmax_pos = 0, rmin_2nd = seg[0].R;
	int rmin = seg[0].R, rmin_pos = 0;
	rep(i, n){
		if(seg[i].L > lmax){
			lmax = seg[i].L;
			lmax_pos = i;
			rmin_2nd = seg[i].R;
		}
		if(seg[i].L == lmax) lmax_pos = -1;
		if(seg[i].R < rmin){
			rmin = seg[i].R;
			rmin_pos = i;
		}
		if(seg[i].R == rmin) rmin_pos = -1;
	}
	int ans = len(lmax, rmin) + len(seg[0].L, seg[0].R);
	rep(i, n){
		ans = qmax(ans, len(lmax, rmin) + len(seg[i].L, seg[i].R));
	}
	if(lmax_pos < 0 || lmax_pos != rmin_pos){
		sort(seg, seg+n);
		for(int i = n-1; i > 0; i--){
			rmin_2nd = qmin(rmin_2nd, seg[i].R);
			ans = qmax(ans, len(lmax, rmin_2nd) + len(seg[i-1].L, rmin));
		}
	}
	cout << ans << endl;
	return 0;
}


#include <cstdio>
#include <algorithm>
#include <vector>
#define file(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)

inline int read()
{
	int data = 0, w = 1; char ch = getchar();
	while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
	if (ch == '-') w = -1, ch = getchar();
	while (ch >= '0' && ch <= '9') data = data * 10 + (ch ^ 48), ch = getchar();
	return data * w;
}

const int N(2e5 + 10), Mod(1e9 + 7);
int fac[N], inv[N], f[N], n, m, A, B;
int C(int n, int m) { return 1ll * fac[n + m] * inv[m] % Mod * inv[n] % Mod; }
int fastpow(int x, int y)
{
	int ans = 1;
	for (; y; y >>= 1, x = 1ll * x * x % Mod)
		if (y & 1) ans = 1ll * ans * x % Mod;
	return ans;
}

int main()
{
	n = read() - 1, m = read() - 1, A = read() - 1, B = read() - 1, fac[0] = inv[0] = 1;
	if (A == n || B == m) return puts("0"), 0;
	for (int i = 1; i <= n + m; i++) fac[i] = 1ll * fac[i - 1] * i % Mod;
	inv[n + m] = fastpow(fac[n + m], Mod - 2);
	for (int i = n + m - 1; i; i--) inv[i] = 1ll * inv[i + 1] * (i + 1) % Mod;
	int ans = C(n, m);
	for (int i = 0; i <= A; i++)
		ans = (ans - 1ll * C(i, m - B - 1) * C(n - i, B) % Mod + Mod) % Mod;
	printf("%d\n", ans);
	return 0;
}

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

typedef long long ll;
const ll MAXN = 2e5+10;
const ll MOD = 1e9+7;

ll H, W, A, B, ans = 0, fac[MAXN], inv[MAXN];

int main() {
    scanf("%lld%lld%lld%lld", &H, &W, &A, &B);
    inv[1] = inv[0] = 1;
    fac[1] = fac[0] = 1;
    for (ll i = 2; i <= MAXN - 10; i++) {
        inv[i] = inv[MOD % i] * (MOD - MOD / i) % MOD;
        fac[i] = fac[i-1] * i % MOD;
    }
    for (ll i = 2; i <= MAXN - 10; i++) {
        inv[i] = inv[i-1] * inv[i] % MOD;
    }
    for (ll i = 1; i <= H-A; i++) {
        ll tem = (B - 1) + (i - 1);
        ll tql = (W - B - 1) + (H - i);
        ll len = W - B - 1;
        ll now = ((((fac[tem] * inv[i-1] % MOD) * inv[tem-(i-1)] % MOD) % MOD) * (((fac[tql] * inv[len] % MOD) * inv[tql - len] % MOD) % MOD)) % MOD;
        ans = (ans + now) % MOD;
    }
    printf("%lld\n", ans % MOD);
    return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
#define all(x) (x).begin(),(x).end()
#define cyes cout<<"YES"<<endl
#define cno cout<<"NO"<<endl
#define sp <<" "<<
#define cst(x) cout<<fixed<<setprecision(x)
#define pi 3.14159265359
#define mod 1000000007
struct edge {
    int to;
    int weight;
    edge(int t, int w) : to(t),weight(w) {}
};
using namespace std;
using ll = long long;
using ld = long double;
using Graph = vector<vector<int>>;
using que_a = priority_queue<int, vector<int>, greater<int> >;
using que_d = priority_queue<int>;
using pint = pair<int,int>;
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; }

int main(){

    int n; cin >> n;
    ll ans = -1;
    int pre = -1;
    bool ok = true;
    rep(i,n){
        int a; cin >> a;
        if(a > pre+1) ok = false;
        else if(a == pre+1) ans++;
        else ans += a;
        pre = a;
    }
    ok? cout << ans << endl : cout << -1 << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[214514];
int main() {
	ll n;
	cin>>n;
	for(int i=0;i<n;i++)cin>>a[i];
	ll ans=0;
	if(a[0]!=0)cout<<-1<<endl;
	else{
		ll cnt=1;
		for(int i=1;i<=n;i++){
			if(a[i]==a[i-1])cnt++;
			else if(a[i]>a[i-1]){
				if(a[i]-a[i-1]>1){
					cout<<-1<<endl;
					return 0;
				}
				ans+=(cnt-1)*a[i-1];
				cnt=1;
			}else{
				ans+=cnt*a[i-1];
				cnt=1;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}