#include<algorithm>
#include<iostream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
#define neinf 0xc0c0c0c0c0c0c0c0ll
#define inf 0x3f3f3f3f3f3f3f3fll
#define uint unsigned int
#define ull unsigned ll
#define HgS 1000000007
#define ll long long
#define reg register
#define opr operator
#define ret return
#define gc getchar
#define pc putchar
#define cst const
#define db double
#define il inline
il ll rd()
{
	reg ll res=0,lab=1;
	reg char ch=gc();
	while((ch<'0'||ch>'9')&&ch!=EOF)
	{if(ch=='-')lab=-lab;ch=gc();}
	while(ch>='0'&&ch<='9')
		res=(res<<3)+(res<<1)+(ch&15),ch=gc();
	return res*lab;
}
il void prt(ll x,char t='\n')
{
	static char ch[40];reg int tp=0;
	if(!x){fputs("0",stdout);if(t)pc(t);return;}
	if(x<0)pc('-'),x=-x;
	while(x)ch[++tp]=(x%10)^48,x/=10;
	while(tp)pc(ch[tp--]);
	if(t)pc(t);
}
il ll umax(ll a,ll b){return a>b?a:b;}
il ll umin(ll a,ll b){return a<b?a:b;}
il ll uabs(ll x){return x>0?x:-x;}
il ll qpow(ll n,ll e=HgS-2,ll p=HgS)
{
	reg ll res=1;
	while(e){if(e&1)res=res*n%p;n=n*n%p;e>>=1;}
	return res;
}
ll T,L,R;
int main()
{
	T=rd();
	while(T --> 0)
	{
		L=rd();R=rd();
		if(2*L>R)prt(0);
		else prt((R-2*L+1)*(R-2*L+2)/2);
	}
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define int 					long long
//#define double 					long double
#define max(x,y) 				(((x)>(y))?(x):(y))
#define min(x,y) 				(((x)<(y))?(x):(y))
#define all(v) 					v.begin(),v.end()
#define vi 						vector<int>
#define MOD 					1000000007
#define inf 					1e18
#define ps(num,precision) 		fixed<<setprecision(precision)<<num
#define md(arr,n,type) 			type *arr=new type[n]

void inout(){
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
	#endif
}

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

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

void SieveOfEratosthenes(int n){
	bool prime[n+1];
	memset(prime,true,sizeof(prime));
	for(int p=2;p*p<=n;p++){
		if(prime[p]){
			for(int i=p*p;i<=n;i+=p){
				prime[i]=false;
			}
		}
	}

	for(int i=2;i<=n;i++){
		if(prime[i]){
		}
	}
}
int printDivisors(int n)
{
	int sum=0;
    for (int i=1; i<=sqrt(n); i++)
    {
        if (n%i == 0)
        {
            if (n/i == i)
                sum+=1;
            else{
                sum+=2;
            }
        }
    }
    return sum;
}

void solve(){
    int n;
	cin>>n;
	int a[n];
	int min;
	int ans=0;
	int con=0;
	vector<pair<int,int>> b;
	for(int i=0;i<n;i++){
		cin>>a[i];
		b.push_back(make_pair(a[i],i));
	}
	sort(all(b));
	for(int i=0;i<n;i++){
		min=a[i];
		if(ans<a[i]){
			ans=a[i];
		}
		for(int j=i+1;j<n;j++){
			if(min>a[j]){
				min=a[j];
			}
			if((j-i+1)*min>ans){
				ans=(j-i+1)*min;
			}
		}
	}
	cout<<ans;
}
int32_t main(){
	//inout();
	int t=1;
	//cin>>t;
	while(t--){
		solve();
	}
	return 0;
}


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

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> struct P {
  T x;
  T y;
  P(T x, T y): x(x), y(y) {}
};
const int DX[4] = {1, 0, -1, 0};
const int DY[4] = {0, 1, 0, -1};
#define int long long
#define rep(i, n) for (int i = 0; i < (n); i++)
constexpr long long INF = 1000000000000000000LL + 8;

signed main() {
  int N, M;
  cin >> N >> M;
  vector<int> A(M);
  rep(i, M) cin >> A[i];
  sort(A.begin(), A.end());
  A.push_back(N + 1);

  // 最小の連続白を探してスタンプにする
  // スタンプを押す配列も作っていく
  int len = INF;
  vector<int> s;
  int current = 0;
  rep(i, M + 1) {
    int l = A[i] - current;
    if (l > 1) {
      chmin(len, l - 1);
      s.push_back(l - 1);
    }
    current = A[i];
  }

  // スタンプを足していく
  int result = 0;
  rep(i, s.size()) {
    result += (s[i] + len - 1) / len;
  }

  cout << result << endl;
  return 0;
}

#include <bits/stdc++.h>

#define EOL "\n";
typedef long long ll;

using namespace std;

int main(){
    int N, W;
    cin >> N >> W;
    vector<pair<int, int>> event;
    int s, t, p;
    for (int i = 0; i < N; ++i) {
        cin >> s >> t >> p;
        event.push_back(make_pair(s, p));
        event.push_back(make_pair(t, -p));
    }

    sort(event.begin(), event.end());
    long long crr = 0;
    for (auto x : event) {
        crr += x.second;
        if (crr > W) {
            cout << "No";
            return 0;
        }

    }

    cout << "Yes";

    return 0;
}


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

// @@ !! LIM()

int main(/* int argc, char *argv[] */) {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << setprecision(20);

  ll N; cin >> N;
  vector<ll> A(N), B(N);
  for (ll i = 0; i < N; i++) cin >> A[i];
  for (ll i = 0; i < N; i++) cin >> B[i];
  ll maxA = 0;
  ll minB = 1001;
  for (ll i = 0; i < N; i++) {
    maxA = max(A[i], maxA);
    minB = min(B[i], minB);
  }
  if (minB >= maxA) {
    cout << minB - maxA + 1 << endl;
  }else {
    cout << 0 << endl;
  }

  return 0;
}

#include <iostream>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <vector>
//#include "maybe.h"
#include <limits>
#include <bitset>
#include <queue>
#include <algorithm>
#include <list>
#include <cmath>
#include <cstring>
#include <bits/stdc++.h>

using namespace std;

using ull = unsigned long long;
using ll = long long;
using ui = unsigned int;
using PI = pair<int, int>;

void func() {
    int N;
    ll md = 0;
    ll cd = 0;
    ll ed_s = 0;
    cin >> N;
    for (int i = 0; i < N; i++) {
        ll x;
        cin >> x;
        md += abs(x);
        cd = max(cd, abs(ll(x)));
        ed_s += x * x;
    }
    double ed = sqrt(ed_s);
    cout << fixed << setprecision(15);

    cout << md << endl;
    cout << ed << endl;
    //printf("%.15f\n", ed);
    cout << cd << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    func();
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
mt19937 rnd(time(0));

//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("fast-math")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
#define ios ios_base::sync_with_stdio(0);cout.tie(0);cin.tie(0);
#define int long long
#define sz(a) (int)a.size()
#define all(a) a.begin(),a.end()
//ll p = 131;
int mod = 1e9 + 7;
int inf = 3000000000000000000;

void solve() {
    int n;
    string s;
    cin >> n >> s;
    int f = 1;
    int q;
    cin >> q;
    while (q-- > 0) {
        int t, a, b;
        cin >> t >> a >> b;
        if (t == 1) {
            --a, --b;
            if (!f)
                a = (a + n) % (2 * n), b = (b + n) % (2 * n);
            swap(s[a], s[b]);
        } else {
            f = 1 - f;
        }
    }
    if (f) {
        cout << s;
    } else {
        cout << s.substr(n) << s.substr(0, n);
    }
}

signed main() {

//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    ios;
//    int t;
//    cin >> t;
//    while (t-- > 0)
    solve();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define Mp make_pair
#define pb push_back

using ll = long long;
using db = double;
using pii = pair<int, int>;
using vi = vector<int>;
mt19937 mrand(time(0));
ll get(ll r) { return ((ll)mrand() * mrand() % r + r) % r; }
ll get(ll l, ll r) { return get(r - l + 1) + l; }

int n, x[20], y[20], z[20], f[1 << 17][17], ans = 1e9;
int dis(int i, int j) { return abs(x[i] - x[j]) + abs(y[i] - y[j]) + max(0, z[j] - z[i]); }
signed main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
        scanf("%d %d %d", &x[i], &y[i], &z[i]);
    memset(f, 0x3f, sizeof(f)), f[1][0] = 0;
    for(int S = 2; S < 1 << n; S++)
        for(int i = 0; i < n; i++) if(S >> i & 1)
            for(int j = 0; j < n; j++) if((S >> j & 1) && j != i)
                f[S][i] = min(f[S][i], f[S ^ (1 << i)][j] + dis(j, i));
    for(int i = 0; i < n; i++) ans = min(ans, f[(1 << n) - 1][i] + dis(i, 0));
    printf("%d\n", ans);
    fprintf(stderr, "time=%.4f\n", (db)clock()/CLOCKS_PER_SEC);
    return 0;
}


#include <iostream>
using namespace std;
int main(){
  int N,K,M;
  cin>>N>>K>>M;
  int A[110];
  for (int i=0; i<N-1; i++) cin>>A[i];
  int points=N*M;
  int sum=0;
  for ( int i=0; i<N-1; i++) sum+=A[i];
  int t=points-sum;
  if (t<=0) cout<<'0'<<endl;
  else if (t<=K) cout<<t<<endl;
  else cout<<"-1"<<endl;
}


#include <bits/stdc++.h> //Andrei Alexandru a.k.a Sho10
#define ll long long
#define double long double
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define all(a) (a).begin(), (a).end()
#define sz size
#define f first
#define s second
#define pb push_back
#define er erase
#define in insert
#define mp make_pair
#define pi pair
#define rc(s) return cout<<s,0
#define endl '\n'
#define mod 1000000007
#define PI 3.14159265359
#define MAXN 100005
#define INF 1000000005
#define LINF 1000000000000000005ll
#define CODE_START  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
ll x,y,a,b,ans=0;
int32_t main(){
CODE_START;
cin>>x>>y;
cin>>a>>b;
while(x<b&&x*a<y){
    x*=a;
    ans++;
}
ans+=(y-1-x)/b;
cout<<ans<<endl;
}

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

// a + bi <=> a + bx
using P = complex<double>;

int main(){
    int n, m, k;
    cin >> n >> m >> k;
    vector<int> a(k);
    for(int i=0; i<k; ++i) cin >> a[i];
    // 「振出しに戻る」が M マス連続していないことを確認する
    int conti_cnt = 1;
    for(int i=0; i<k; ++i){
        if(i > 0 && a[i] - a[i-1] == 1){
            conti_cnt += 1;
        }else{
            conti_cnt = 1;
        }
        if(conti_cnt >= m){
            cout << -1 << endl;
            return 0;
        }
    }

    // 求める値（マス 0 からマス n に到達するために必要な回数の期待値）を X とする
    // dp[i] = {マス i からマス n に到達するために必要な回数の期待値}
    //       = 0                                 （ i>=n のとき）
    //         X                                 （マス i が「振出しに戻る」のとき）
    //         (dp[i+1] + ... + dp[i+m]) / m + 1 （それ以外）
    vector<P> dp(n+m+1, 0);
    for(int i=0; i<k; ++i){
        dp[a[i]] = P{0, 1};
    }
    P s{0, 0}; // 累積和
    for(int i=n-1; i>=0; --i){
        s += dp[i+1] - dp[i+m+1];
        if(dp[i].imag() == 0){
            dp[i] = s / double(m) + 1.0;
        }
    }
    // X = a + bX より X=a/(1-b)
    cout << setprecision(20) << dp[0].real() / (1 - dp[0].imag()) << endl;
    return 0;
}


#include <bits/stdc++.h>

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

typedef long long ll;

const int INF = 1 << 30;
const ll LLINF = 1LL << 60;

int mod = 1000000007;

int dp[3030][10][50];

void init(){
    rep(i, 3030) rep(j, 10) rep(k, 50) dp[i][j][k] = 0;
    dp[0][0][0] = 1;
}

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N; cin >> N;
    vector<int> A(N), B(N), C(N), D(N), E(N);
    rep(i, N) cin >> A[i] >> B[i] >> C[i] >> D[i] >> E[i];
    int ok = 0, ng = INF;
    int m = (ok+ng)/2;
    while(abs(ok-ng) > 1){
        //cout << "m: " << m << endl;
        init();
        rep(i, N){
            int val = 0;
            if(A[i] >= m) val += (1 << 4);
            if(B[i] >= m) val += (1 << 3);
            if(C[i] >= m) val += (1 << 2);
            if(D[i] >= m) val += (1 << 1);
            if(E[i] >= m) val += (1 << 0);
            //cout << i << ": " << val << endl;
            for(int ninzuu = 0; ninzuu < 5; ninzuu++){
                rep(now_state, (1 << 5)){
                    dp[i+1][ninzuu][now_state] = max(dp[i+1][ninzuu][now_state], dp[i][ninzuu][now_state]);
                    dp[i+1][ninzuu+1][now_state|val] = max(dp[i+1][ninzuu+1][now_state|val], dp[i][ninzuu][now_state]);
                }
            }
        }
        if(dp[N][3][(1 << 5)-1] == 1) ok = m;
        else ng = m;
        m = (ok+ng)/2;
    }
    cout << ok << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int,int> pii;
typedef long long ll;
const long long MOD=1000000007;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define rep2(i,m,n) for(ll i=(m);i<(n);i++)
#define ALL(v) v.begin(), v.end()
#define pb push_back

const int INF=1e9;

int n,m,k;

vector<int> c(20);

vector<vector<int>> graph(200000,vi(0));

vector<vector<int>> dp(1<<20,vi(20,INF));

vector<vector<int>> dis(20,vi(20));

int bfs(int s, int t){
    vi seen(n,-1);
    seen[s]=0;

    queue<int> q;
    q.push(s);
    while (!q.empty()){
        int x=q.front();
        q.pop();
        for (int next:graph[x]){
            if (seen[next]==-1) {
                seen[next]=seen[x]+1;
                q.push(next);
            }
        }
    }

    return seen[t];

}

int rec(int S, int v){
    if (dp[S][v]!=INF) return dp[S][v];

    if (S==(1<<v)) return dp[S][v]=0;

    rep(i,k){
        if ((S>>i & 1) and (i!=v)){
            dp[S][v]=min(rec(S & ~(1<<v),i)+dis[v][i], dp[S][v]);
        }
    }

    return dp[S][v];

}

int main(){

    cin>>n>>m;

    rep(i,m){
        int a,b;
        cin>>a>>b;
        a--;
        b--;
        graph[a].pb(b);
        graph[b].pb(a);
    }

    cin>>k;

    rep(i,k){
        int tmp;
        cin>>tmp;
        tmp--;
        c[i]=tmp;
    }

    rep(i,k){
        rep(j,k){
            if (i<=j) dis[i][j]=bfs(c[i],c[j]);
            else dis[i][j]=dis[j][i];
        }
    }

    int ans=1e9;

    rep(i,k){
        rep(j,k){
            if (dis[i][j]==-1) ans=-1;
        }
    }

    if (ans!=-1){
        rep(i,k){
            ans=min(ans,rec((1<<k)-1,i)+1);
        }
    }

    cout<<ans<<endl;

}


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

int A, B, C;

int qp(int x, int y, int P) {
    int z = 1;
    for (; y; y >>= 1, x = 1LL * x * x % P) {
        if (y & 1) z = 1LL * z * x % P;
    }
    return z;
}

int main() {
    scanf("%d %d %d", &A, &B, &C);
    if (B <= 4 && C <= 4) {
        A = qp(A % 10, qp(B, C, 998244353), 10);
    } else {
        B = qp(B % 4, C, 4);
        A = qp(A % 10, B + 4, 10);
    }
    printf("%d\n", A);
    return 0;
}


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

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

constexpr ll mod=998244353;

ll mod_pow(ll a,ll b){
    a%=mod;
    if(b==0)return 1;
    if(b==1)return a;
    ll res=mod_pow(a,b/2)%mod;
    res*=res; res%=mod;
    if(b%2)res*=a;
    return res%mod;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    vector<ll> a(n);
    ll sum=0;
    ll po=1;
    for(int i=0;i<n;i++){
        cin >> a[i];
    }
    sort(a.begin(), a.end());
    for(int i=1;i<n;i++){
        (sum+=po*a[i]%mod)%=mod;
        po*=2; po%=mod;
    }
    ll res=0;
    for(int i=0;i+1<n;i++){
        (res+=a[i]*sum%mod)%=mod;
        // cout << res << " " << sum << endl;
        sum-=a[i+1];
        sum*=mod_pow(2,mod-2);
        sum%=mod;
    }
    for(int i=0;i<n;i++){
        (res+=a[i]*a[i])%=mod;
    }
    if(res<0)res+=mod;
    cout << res << endl;
}

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

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

  long long box[210];
  for(int i=0;i<=199;i++){
    box[i]=0;
  }

  for(long long i=0;i<n;i++){
    long long a;
    cin >> a;
    a %= 200;
    if(a < 0){ a += 200; }
    if(a >= 200){ a -= 200; }
    box[a] += 1;
  }

  long long ans = 0;
  for(int i = 0 ; i <= 199 ; i++){
    ans += (box[i] * (box[i] - 1)) / 2;
  }

  cout << ans;
  return 0;
}


#include<iostream>
#include<algorithm>

using namespace std;

typedef long long ll;

const int N=100010;

int n;
ll a[N];
ll ans=1e19;

void dfs(ll i,ll pre,ll xo)//x表示当前的位置，我们通过位置去判断是否需要去异或或者或
{                            //pre表示我们当前的答案，xo表示我们前面统计的所以答案的异或起来的数
    if(i>n)
    {
        ans=min(ans,xo^pre);
        return ;
    }
    dfs(i+1,pre|a[i],xo);//这个就是a[i]还没有自立门户，我们就直接或上就行了

    dfs(i+1,a[i],pre^xo);//表示我们a[i]已经自立门户了，我们就去统后面的x0
                        //就是去统计之前的异或和来方便后面的计算

}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];

    dfs(1,0,0);

    cout<<ans;
    return 0;
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

typedef long long ll;

#define MOD 1000000007

int main() {
  int n;
  cin >> n;
  vector<ll> a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
  }
  ll ans = 2e18;
  for (int bit = 0; bit < (1 << n); ++bit) {
    vector<ll> v;
    ll sum = 0;
    for (int i = 0; i < n; ++i) {
      if (bit >> i & 1) {
        v.push_back(sum);
        sum = a[i];
      } else {
        sum |= a[i];
      }
    }
    v.push_back(sum);
    ll res = 0;
    for (int i = 0; i < v.size(); ++i) {
      res ^= v[i];
    }
    ans = min(ans, res);
  }
  cout << ans << endl;
  return 0;
}


/* C - Robot on Grid */
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using pii = pair<int, int>;

const int N = 5e3 + 10;
const int mod = 998244353;
int h, w, n, s[N][N];
char a[N][N];

int ksm(int a, int b, int p)
{
    int res = 1 % p;
    while (b) {
        if (b & 1) res = (ll)res * a % p;
        a = (ll)a * a % p;
        b >>= 1;
    }
    return res;
}

int solve(void)
{
	int inv = ksm(3, mod - 2, mod);
	s[1][1] = 1;
	for (int k = 1; k <= h; ++k) {
		for (int i = 1; i <= w; ++i) {
			if ('R' == a[k][i]) 		s[k][i + 1] = (s[k][i] + s[k][i + 1]) % mod;
			else if ('D' == a[k][i])	s[k + 1][i] = (s[k][i] + s[k + 1][i]) % mod;
			else if ('X' == a[k][i]) {
				s[k][i + 1] = (s[k][i] + s[k][i + 1]) % mod;
				s[k + 1][i] = (s[k][i] + s[k + 1][i]) % mod;
			}
			else {
				int val = (ll)s[k][i] * 2 * inv % mod;
				s[k][i + 1] = (val + s[k][i + 1]) % mod;
				s[k + 1][i] = (val + s[k + 1][i]) % mod;
			}
		}
	}
	return (ll)s[h][w] * ksm(3, h * w - n, mod) % mod;
}

signed main(int argc, char** argv)
{
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
	//	freopen("output.txt", "w", stdout);
	#endif
	while (cin >> h >> w >> n) {
		memset(a, 0, sizeof(a));
		memset(s, 0, sizeof(s));
		for (int k = 1; k <= n; ++k) {
			int x, y;
			char c;
			cin >> x >> y >> c;
			a[x][y] = c;
		}
		cout << solve() << endl;
	}
	return 0;
}

#include <bits/stdc++.h>
#define be(v) (v).begin(),(v).end()
#define pb(q) push_back(q)
#define rep(i, n) for(int i=0;i<n;i++)
#define all(i, v) for(auto& i : v)
typedef long long ll;
using namespace std;
const ll mod=998244353, INF=(1LL<<60);
#define doublecout(a) cout<<fixed<<setprecision(10)<<a<<endl;

///////modint
struct mint {
    ll x; // typedef long long ll;
    mint(ll x=0):x((x%mod+mod)%mod){}
    mint operator-() const { return mint(-x);}
    mint& operator+=(const mint a) {
        if ((x += a.x) >= mod) x -= mod;
        return *this;
    }
    mint& operator-=(const mint a) {
        if ((x += mod-a.x) >= mod) x -= mod;
        return *this;
    }
    mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this;}
    mint operator+(const mint a) const { return mint(*this) += a;}
    mint operator-(const mint a) const { return mint(*this) -= a;}
    mint operator*(const mint a) const { return mint(*this) *= a;}
    mint pow(ll t) const {
        if (!t) return 1;
        mint a = pow(t>>1);
        a *= a;
        if (t&1) a *= *this;
        return a;
    }

    // for prime mod
    mint inv() const { return pow(mod-2);}
    mint& operator/=(const mint a) { return *this *= a.inv();}
    mint operator/(const mint a) const { return mint(*this) /= a;}
};

vector<vector<mint> > dp;
int a[5000][5000];

int main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    ll h, w, k, y, x;
    cin >> h >> w >> k;
    char c;
    memset(a, 0, sizeof(a));
    mint inv3 = mint(3).inv();
    rep(i, k){
        cin >> y >> x >> c;
        y--; x--;
        if(c == 'R') a[y][x] = 1;
        else if(c == 'D') a[y][x] = 2;
        else a[y][x] = 3;
    }
    dp.resize(h, vector<mint> (w, mint(0)));
    dp[0][0] = mint(3).pow(h * w - k);
    rep(i, h){
        rep(j, w){
            if(i < h - 1){
                if(a[i][j] == 2 || a[i][j] == 3){
                    dp[i + 1][j] += dp[i][j];
                }else if(a[i][j] == 0){
                    dp[i + 1][j] += dp[i][j] * inv3 * mint(2);
                }
            }
            if(j < w - 1){
                if(a[i][j] == 1 || a[i][j] == 3){
                    dp[i][j + 1] += dp[i][j];
                }else if(a[i][j] == 0){
                    dp[i][j + 1] += dp[i][j] * inv3 * mint(2);
                }
            }
        }
    }
    cout << dp[h - 1][w - 1].x << endl;
    return 0;
}


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

#define ll long long
#define ld long double
#define F first
#define S second
#define all(v) v.begin(),v.end()
#define sz(v) (int)v.size()
#define precision cout << fixed << setprecision(15);

const int inf = 1e9;
const long long INF = 1e18;
int mod = 1e9 + 7;
const int bit32 = log2(inf) + 3;
const int bit64 = log2(INF) + 3;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
clock_t time_p = clock();

void ktj() {
  time_p = clock() - time_p;
  cerr << "Time elapsed : " << (float)(time_p)/CLOCKS_PER_SEC << "\n";
}

void pre() {}

inline int add(long long a, long long b){a += b; if(a >= mod) a -= mod; return a;}
inline int sub(long long a, long long b){a -= b; if(a < 0) a += mod; return a;}
inline int mul(long long a, long long b){a %= mod; b %= mod; return (int)((long long) a * b % mod);}
inline int modexpo(long long a, long long b){int res = 1; while(b > 0){ if(b & 1) res = mul(res, a); a = mul(a, a); b /= 2;} return res;}
inline int divide(long long a, long long b){return mul(a, modexpo(b, mod - 2));}
inline int inv(long long a){return modexpo(a, mod - 2);}

void solve() {
  long long a, b, c;
  cin >> a >> b >> c;
  mod = 100;
  long long e = modexpo(b, c);
  mod = 10;
  if (e == 0) {
    cout << modexpo(a, 4) << '\n';
  } else {
    long long f = modexpo(a, e);
    cout << f << '\n';
  }
}

#define GOOGLE 0
#define MULTIPLE_TC 0

int32_t main() {

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

  pre();

  int t = 1, T;

  if (MULTIPLE_TC)
    cin >> t;

  for (T = 1; T <= t; T++) {
    if (GOOGLE)
      cout << "Case #" << T << ": ";
    solve();
  }

  ktj();
}

#include <iostream>
#define int long long
using namespace std;

int binpow(int a, int b, int c) {
	int ret = 1;
	while (b) {
		if (b & 1) ret = ret * a % c;
		a = a * a % c;
		b >>= 1;
	}
	return ret % c;
}

signed main()
{
	int a, b, c; cin >> a >> b >> c;
	a %= 10; b %= 4;
	int exp = binpow(b, c, 4);
	if (exp == 0) exp = 4;
	cout << binpow(a, exp, 10);
	return 0;
}


#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define visit asdf
const int N=2e5+5;

int n;
int a[N],b[N],c[N],p[N];
vector< vector<int> > v;
bool visit[N];

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i);
	for(int i=1;i<=n;i++) scanf("%d",b+i);
	for(int i=1;i<=n;i++) scanf("%d",p+i);
	for(int i=1;i<=n;i++)
		if(a[i]<=b[p[i]] && p[i]!=i) return puts("-1"),0;
	for(int i=1;i<=n;i++) c[i]=b[p[i]];
	for(int i=1;i<=n;i++) b[i]=c[i];

	for(int i=1;i<=n;i++)
	{
		if(visit[i]) continue;
		vector<int> vec;
		vec.pb(i); visit[i]=1;
		int j=i;
		while(p[j]!=i)
		{
			vec.pb(p[j]);
			visit[p[j]]=1;
			j=p[j];
		}
		v.pb(vec);
	}
	printf("%d\n",n-v.size());
	for(int ii=0;ii<v.size();ii++)
	{
		vector<int> vec=v[ii];
		int mn=1e9,u;
		for(int i=0;i<vec.size();i++)
			mn=min(mn,b[vec[i]]);
		for(int i=0;i<vec.size();i++)
			if(b[vec[i]]==mn) u=i;
		for(int i=vec.size()+u;i>u+1;i--)
			printf("%d %d\n",vec[i%vec.size()],vec[(i-1)%vec.size()]);
	}

	return 0;
}

#include <bits/stdc++.h>

using namespace std ;

const int MAX = 2e5 + 10 ;

int n ;
int a[MAX] , b[MAX] , p[MAX] , pos[MAX] ;

vector< pair<int , int> >vp , ans ;

int main()
{
	ios_base::sync_with_stdio(0) ;
	cin.tie(0) ;
	cin>>n ;
	for(int i = 0 ; i < n ; ++i)
		cin>>a[i] ;
	for(int i = 0 ; i < n ; ++i)
		cin>>b[i] ;
	for(int i = 0 ; i < n ; ++i)
	{
		cin>>p[i] ;
		p[i]-- ;
		pos[p[i]] = i ;
		if(b[p[i]] >= a[i] && p[i] != i)
			return cout<<-1<<"\n" , 0 ;
	}
	for(int i = 0 ; i < n ; ++i)
		vp.emplace_back(a[i] , i) ;
	sort(vp.begin() , vp.end()) ;
	for(auto &i : vp)
	{
		int idx = i.second ;
		if(p[idx] == idx)
			continue ;
		int x = pos[idx] ;
		ans.emplace_back(idx+1 , x+1) ;
		swap(p[idx] , p[x]) ;
		pos[idx] = idx , pos[p[x]] = x ;
	}
	cout<<ans.size()<<"\n" ;
	for(auto &i : ans)
		cout<<i.first<<" "<<i.second<<"\n" ;
	return 0 ;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define md 998244353
#define N 200010
#define ll long long
ll a[N], ans = 0;
ll ksm(ll x, ll y) {
	if(y < 0) return 1;
	if(!y) return 1;
	ll l = ksm(x, y / 2);
	if(y % 2) return l * l % md * x % md;
	return l * l % md;
}
int main() {
	int n, i, j;
	scanf("%d", &n);
	for(i = 1; i <= n; i++) scanf("%d", &a[i]);
	sort(a + 1, a + n + 1);
	ll t = 0;
	for(j = 1; j <= n; j++) t = (t + a[j] * ksm(2, j - 2)) % md;
	for(i = 1; i <= n; i++) {
		ans = (ans + a[i] * t) % md;
		t = (((t - a[i] - a[i + 1]) * ksm(2, md - 2) + a[i + 1]) % md + md) % md;
	}
	printf("%lld\n", ans);
	return 0;
}

#include "bits/stdc++.h"
using namespace std;
#define REP(i, n) for(ll i = 0;i < n;i++)
#define ll long long
//#define MOD 1000000007LL
#define MOD 998244353LL
#define doublecout(a) cout<<setprecision(16)<<a<<endl;
using vi = vector<ll>; // intの1次元の型に vi という別名をつける
using vvi = vector<vi>; // intの2次元の型に vvi という別名をつける
using vvvi = vector<vvi>; // intの2次元の型に vvi という別名をつける
const ll llMAX=9223372036854775807LL;
const ll llMIN=-9223372036854775808LL;

void myprint1D(vi &data)
{
  REP(i,data.size())
    cout<<data[i]<<" ";
  cout<<endl;
}

//配列を[y][x]で表示
void myprint2D_T(vvi &data)
{
  REP(i,data.size())
    myprint1D(data[i]);
}

//配列を[x][y]で表示
void myprint2D(vvi &data)
{
  ll l1=data.size();
  ll l2=data[0].size();
  REP(j,l2){
    REP(i,l1)
      cout<<data[i][j]<<" ";
    cout<<endl;
  }
}

//print(a,b...)って使い方
void print1(ll a){cout<<a<<endl;}
void print2(ll a,ll b){cout<<a<<" "<<b<<endl;}
void print3(ll a,ll b,ll c){cout<<a<<" "<<b<<" "<<c<<endl;}
void print4(ll a,ll b,ll c,ll d){cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;}
void print5(ll a,ll b,ll c,ll d,ll e){cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<endl;}

//moddivとnCkとgarner
ll gcd(ll a,ll b){
  ll r = a % b;
  while(r!=0LL){
    a = b;
    b = r;
    r = a % b;
  }
return b;
}

//c剰余下でaをbで割った値
ll moddiv(ll a,ll b,ll c){
	ll x0=c,x1=b,x2,n0=0LL,n1=1LL,n2,t=a%b,m,ans;
	if (t==0LL) return a/b;
		for(int i=0;i<900;i++){
      m=x0/x1;
      x2=x0-x1*m;
      n2=(n0-m*n1)%c;
      if (x2==1LL){
        ans=(n2+c)%c;
        break;
      }
      x0=x1;x1=x2;
      n0=n1;n1=n2;
    }
	return (a+((t*ans)%c)*b-t)/b;
}
//剰余の割ざん

//aのn乗 mod c
ll expmod(ll a,ll n,ll c){
  ll ans=1LL,aa=a,beki=n;
  for(int i=0;i<64;i++){
    if (beki%2==1LL) ans=ans*aa%c;
    aa=aa*aa%c;
    beki/=2LL;
    if (beki==0LL)break;
  }
  return ans;
}

//nCk
vi mulmod(500001);//0!,1!,2!,3!,4!,,,,
void first_nCk(){
  mulmod[0]=1LL;
  for(ll i=1;i<500001;i++){
    mulmod[i]=mulmod[i-1]*i%MOD;
  }
}
ll nCk(ll nn,ll kk){
  return moddiv(mulmod[nn],mulmod[kk]*mulmod[nn-kk]%MOD,MOD);
}
ll modinv(ll a,ll b){
  return moddiv(1,a%b,b);
}

//条件ar<a,br<b
ll garner(__int128_t a,__int128_t b,__int128_t ar,__int128_t br){
  if (gcd(a,b)==1){
    if (a==1){
      return br;
    }
    if (b==1){
      return ar;
    }

    __int128_t tmp=(br-ar)%b*modinv(a,b)%b;
    if (tmp<0)tmp+=b;
    return ar+tmp*a;
  }else{//299%200=99,299%300=299とかのとき
    //ありえない場合-1を出力
    __int128_t g=gcd(a,b);
    if (ar>br){
      __int128_t rr=ar-br;
      if (rr%g!=0){
        return -1;
      }
      __int128_t rrg=rr/g;
      __int128_t ret=garner(a/g,b/g,rrg,0);
      return ret*g+br;
    }else{
      __int128_t rr=br-ar;
      if (rr%g!=0){
        return -1;
      }
      __int128_t rrg=rr/g;
      __int128_t ret=garner(a/g,b/g,0,rrg);
      return ret*g+ar;
    }
  }
}
ll n,k,x,y;

int main(){
  ll ans=0;
  cin >> n;
  vi a(n),b(n),c(n);
  REP(i,n) cin>>a[i];
	sort(a.begin(), a.end());
	ll w=1;
	for(ll i=1;i<n;i++){
		b[i]=a[i]*w%MOD;
		w=w*2%MOD;
	}

	ll cc=0;
	for(ll i=1;i<n;i++){
		cc+=b[i];
	}
	cc%=MOD;

	for(ll i=0;i<n;i++){
		/*
		for(ll j=i+1;j<n;j++){
			//a[i]が最小a[j]が最大が何個あるか
			ll sc=a[i]*a[j]%MOD;
			sc=sc*expmod(2,j-i-1,MOD)%MOD;
			ans+=sc;

		}*/

		if (i==n-1)break;
		ans+=a[i]*cc%MOD;
		ans%=MOD;
		cc=cc-a[i+1]+MOD;
		cc%=MOD;
		cc=moddiv(cc,2,MOD);
	}

	for(ll i=0;i<n;i++){
		ans+=a[i]*a[i]%MOD;
		ans%=MOD;
	}
	/*
	最後に1この場合を足す
	*/

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


#include <bits/stdc++.h>
#define pb push_back
#define sz size()
#define all(c) (c).begin(), (c).end()

using namespace std;

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

const int MOD = 1e9 + 7;
const int maxn = 5e5 + 7;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int a, b, c;
    cin >> a >> b >> c;
    cout << 21 - a - b - c << '\n';
    return 0;
}

//*** Author: ShlokG ***//
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
template<class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k)  returns iterator to kth element starting from 0
// order_of_key(k) returns count of elements strictly smaller than k
#define fix(f,n) std::fixed<<std::setprecision(n)<<f
#define epsi (double)(0.00000000001)
typedef long long int ll;
typedef unsigned long long int ull;
#define vi vector<ll>
#define pii pair<ll,ll>
#define vii vector<pii>
#define max(a,b) ((a>b)?a:b)
#define min(a,b) ((a>b)?b:a)
#define min3(a,b,c) min(min(a,b),c)
#define max3(a,b,c) max(max(a,b),c)
#define ff(a,b,c) for(int a=b; a<=c; a++)
#define frev(a,b,c) for(int a=c; a>=b; a--)
#define REP(a,b,c) for(int a=b; a<c; a++)
#define pb push_back
#define mp make_pair
#define endl "\n"
#define all(v) v.begin(),v.end()
#define sz(a) (ll)a.size()
#define F first
#define S second
#define ld long double
//#define INF 2000000000000000000
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define ub upper_bound
#define lb lower_bound
#define setbits(x) __builtin_popcountll(x)
#define trav(a,x) for(auto &a:x)
#define make_unique(v) v.erase(unique(v.begin(), v.end()), v.end())
#define rev(arr) reverse(all(arr))
#define gcd(a,b) __gcd(a,b);
#define ub  upper_bound // '>'
#define lb  lower_bound // '>='
#define qi queue<ll>
#define si stack<ll>

const long double PI = acos(-1);

mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
    uniform_int_distribution<int> uid(0,lim-1);
    return uid(rang);
}

bool prime[200001];
void SieveOfEratosthenes(){
    memset(prime, true, sizeof(prime));
    prime[1]=false;
    for(ll p=2; p*p<=200000; p++){
        if(prime[p] == true){
            for (int i=p*p; i<=200000; i += p)
                prime[i] = false;
        }
    }
    return;
}

ll gcdExtended(ll a, ll b, ll *x, ll *y){
    if(a == 0){
        *x = 0;
        *y = 1;
        return b;
    }
    ll x1, y1;
    ll gcd = gcdExtended(b%a, a, &x1, &y1);
    *x = y1 - (b/a) * x1;
    *y = x1;
    return gcd;
}

ll modInverse(ll a, ll m){
    ll x, y;
    ll g = gcdExtended(a, m, &x, &y);
        ll res = (x%m + m) % m;
        return res;
}

ll binary_Search(vector<ll>&arr,ll key){
    ll l=0,r=arr.size()-1;
    ll ans;
    while(l<=r){
        ll mid=(l+r)/2;
        ll value=arr[mid];
        if(value>key){
            r=mid-1;
        }else if(value==key){
            return mid;
        }else{
            l=mid+1;
        }
    }
    return -1;
}

ll power(ll x,ll y,ll p){
    ll res = 1;
    x = x % p;
    if (x == 0) return 0;
    while (y > 0){
        if (y & 1)
            res = (res*x) % p;
        y = y>>1;
        x = (x*x) % p;
    }
    return res;
}

const int N=1e5+5;
const ll INF=1e18;

void solve(){
    ll a,b,c;
    cin >> a >> b >> c;
    a*=a;
    b*=b;
    c*=c;
    if((a+b)<(c)){
        cout << "Yes\n";
    }else{
        cout << "No\n";
    }
}

int main(){
    fast;
    //freopen ("auxiliary.in","r",stdin);
    //freopen ("auxiliary.out","w",stdout);
    int test=1;
    //cin >> test;
    while(test--){
        solve();
    }
    return 0;
}


#include <bits/stdc++.h>
#pragma GCC target("arch=skylake-avx512")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
using ll = long long;
using ld = long double;
using Graph = vector<vector<int>>;
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rrep(i, n) for (int i = 1; i < (int)(n+1); ++i)
const long long INF = 1LL<<60;
const long long MOD = 1000000007;
const long long mod = 998244353;
int ri() {
	int n;
	scanf("%d", &n);
	return n;
}
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;
}
int main() {
  	int N,M,Q;
    cin>>N>>M>>Q;
    vector<pair<int,int>>W(N);
    vector<int>X(M);
    rep(i,N){
        cin>>W[i].second;
        cin>>W[i].first;
    }
    rep(i,M){
        cin>>X[i];
    }
    int ans=0;
    sort(W.rbegin(),W.rend());
    rep(i,Q){
        int L,R;
        cin>>L>>R;
        int score=0;
        int cn=M-(R-L+1);
      	if(cn!=0){
        vector<int>box(cn);
        vector<bool>H(cn,false);
        cn=0;
        rep(j,M){
            if(L-1<=j&&j<=R-1){}
            else{
                box[cn]=X[j];
                cn++;
            }
        }
        sort(box.begin(),box.end());
        rep(j,N){
            rep(k,cn){
                if(H[k]==false&&W[j].second<=box[k]){
                    H[k]=true;
                    score+=W[j].first;
                    k=cn;
                }
            }
        }
        }
        cout<<score<<endl;
    }
}

/*

  _|_|                              _|  _|    _|
_|    _|  _|  _|_|  _|_|_|_|        _|  _|  _|
_|    _|  _|_|          _|          _|  _|_|
_|    _|  _|          _|      _|    _|  _|  _|
  _|_|    _|        _|_|_|_|    _|_|    _|    _|

*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
//#define ls (rt<<1)
//#define rs (rt<<1|1)
#define vi vector<int>
#define pb push_back
#define mk make_pair
#define pii pair<int,int>
#define rep(i,a,b) for(int i=(a),i##end=(b);i<=i##end;i++)
#define fi first
#define se second
typedef long long ll;
using namespace std;
const int maxn=1<<19;
int dp[maxn];//max use side
bool ck[maxn];
int g[20][20];
int cnt[maxn];
int main(){
	ios::sync_with_stdio(0);
	int n,m;cin>>n>>m;
	rep(i,1,m){
		int a,b;cin>>a>>b;
		g[a][b]=g[b][a]=1;
	}
	rep(i,1,n)g[i][i]=1;
	memset(dp,0x3f,sizeof(dp));
	rep(mask,0,1<<n){
		vi po;
		rep(j,1,n){
			if(mask&(1<<(j-1)))po.pb(j);
		}
		ck[mask]=1;
		for(int i=0;i<po.size();i++)
		for(int j=i;j<po.size();j++)
		if(!g[po[i]][po[j]]){ck[mask]=0;break;}
		if(ck[mask]){
			dp[mask]=1;
		}
	}
	rep(i,1,n)dp[1<<(i-1)]=1;
	rep(mask,0,1<<n){
		int left=(1<<(n))-1;
		left^=mask;int bl=left;
		for(int i=bl;i;i=(i-1)&bl){
			if(ck[i])dp[i|mask]=min(dp[i|mask],dp[mask]+1);
		}
	}
	cout<<dp[(1<<(n))-1];
	return 0;
}


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

int modpow(int p, long long n, int mod) {
    if (n == 0) return 1;
    int t = modpow(p, n / 2, mod);
    return n % 2 == 0 ? 1LL * t * t % mod : 1LL * t * t % mod * p % mod;
}

int main() {
  long long N;
  int M;
  cin >> N >> M;
  cout << (modpow(10, N, M * M) / M) % M << endl;
}

#include<bits/stdc++.h>
#define int long long
#define pb emplace_back
#define INF 0x3f3f3f3f
#define f first
#define s second
#define FOR(i, n) for(int i = 1; i <= n; i ++)
#define FFOR(i, a, b) for(int i = a; i <= b; i ++)
#define pii pair<int, int>
#define mod 1000000007
#define all(x) x.begin(), x.end()
#define mem(x, a) memset(x, a, sizeof(x))
#define loli ios_base::sync_with_stdio(0), cin.tie(0)
using namespace std;
const int maxn = 1e6 + 50;
int n, m;
unordered_set<int> st;
vector<int> vc;

signed main(){
	loli;
	cin >> n >> m;
	int t = 1LL;
	st.reserve(10000000);
	while(1) {
		if(st.find(t) != st.end()) {
			break;
		}
		else {
			st.insert(t);
			vc.pb(t);
		}
		t = t * 10LL % (m * m);
	}
	//cout << t << "\n";
	//cout << st.size() << "\n";
	//for(int i : vc) cout << i << " "; cout << "\n";
	int i = 0;
	for(; i < (int)vc.size(); i ++) if(vc[i] == t) break;
	//cout << "aaa" << i << "\n";
	if(n < i) {
		cout << vc[n] / m << "\n";
		return 0;
	}
	n -= i;
	int ssz = (int)vc.size() - i;
	int tans = vc[n % ssz + i] / m;
	cout << tans << "\n";
}


//x<<y=x*2^y,x>>y=x/2^y
//1e5+3 is prime
// in a matrix, all elements of a primary diagonal have constant diff of coordinates
// and a secondary diagonal has constant sum of coordinates
//use ll() for using an integer in self-built fn
//(x&-x) bitwise and of (x and its 2's complement) returns (last set bit)
//eg if x=1010 then it will return 0010
// careful dont print empty container(run time error)
//v.erase O(n)
//use ("\n") instead of endl as endl flushes the output buffer
//every time so takes more time than \n (TLE)
//stoll() and to_string((less than 1e19))
//INT_MAX is approx 3e10
//For sets use set_name.lower_bound(x)(strictly O(logn))
//NOT lb(all(s),x)(O(logn) for random access (eg vector) but for sets it is O(n));
#include<bits/stdc++.h>
typedef long long int ll;
#define ull unsigned long long int
#define lld long double
#define endl "\n"
#define fi first
#define sec second
#define sp setprecision
#define lb lower_bound
#define ub upper_bound
#define For(i, a, b) for(long long int i = (a); i <= (b); i++)
#define Forr(i, a, b) for(long long int i = (a); i >= (b); i--)
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define vll vector<ll>
#define pll pair<ll,ll>
#define plld pair<lld,lld>
#define vlld vector<lld>
#define vi vector<int>
#define vch vector<char>
#define sll set<ll>
#define sch set<ch>
#define vpll vector< pair<ll,ll> >
#define vpii vector< pair<int,int> >
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define mll map<ll, ll>
#define mcll map<char,ll>
#define sz(container) ll((container).size())
#define fill(a,b) memset(a, b, sizeof(a))
#define fast_io ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
using namespace std;
#define PI 3.1415926535897932384626
const ll mod=1000000007;
//const ll dx[4]={-1, 0, 1, 0} , dy[4]={0, 1, 0, -1};
const ll dxx[8]={-1, -1, 0, 1, 1, 1, 0, -1} , dyy[8]={0, 1, 1, 1, 0, -1, -1, -1};
string ds="RLDU";

/***************************************
struct cmp
{
    bool operator() (const pll &a, const pll &b)  const
    {
        ll lena = a.sec - a.fi + 1;
        ll lenb = b.sec - b.fi + 1;
        if (lena == lenb) return a.fi < b.fi;
        return lena > lenb;
    }
};
********************************/

ll lcm(ll a, ll b)
{
    ll g=__gcd(a, b);
    return a/g*b;
}

ll binpow(ll a, ll b,ll m)
{
    a %= m;
    ll res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = res * a % m;
        a = a * a % m;
        b >>= 1;
    }
    return res;
}
ll Pow(ll a, ll b)
{
    ll res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = res * a;
        a = a * a ;
        b >>= 1;
    }
    return res;
}
ll modinv(ll n,ll m)
{
    return binpow(n, m - 2,m);
}

/*******************************************coding********/
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    fast_io;
    ll T=1;//cin>>T;
    For(i,1,T)
    {
        ll n;cin>>n;
        vector<tuple<ll,ll,ll>>v;
        For(j,1,n)
        {
            ll x,y,z;cin>>x>>y>>z;
            v.pb({x,y,z});
        }
        ll dis[n][n];
        ll N=1ll<<n;
        ll cost[n][N]={};
        For(j,0,N-1) For(k,0,n-1) cost[k][j]=1e15;
        cost[0][1]=0;
        For(j,0,n-1)
        {
            For(k,0,n-1)
            {
                auto [x1,y1,z1]=v[j];
                auto [x2,y2,z2]=v[k];
                dis[j][k]=abs(x1-x2)+abs(y1-y2)+max(0ll,z2-z1);
            }
        }
        for(ll j=1;j<N;j+=2)
        {
            For(i,1,n-1)
            {
                if(j&(1ll<<i)) continue;
                For(k,0,n-1)
                {
                    cost[i][j|(1ll<<i)]=min(cost[i][j|(1ll<<i)],cost[k][j]+dis[k][i]);
                }
            }
        }
        ll ans=1e15;
        For(j,1,n-1) ans=min(ans,cost[j][N-1]+dis[j][0]);
        cout<<ans;
    }
}

#include <bits/stdc++.h>

using namespace std;

int dist(vector<array<int, 3>> &vp, int i, int j) {
  auto [a, b, c] = vp[i];
  auto [p, q, r] = vp[j];
  return abs(p - a) + abs(q - b) + max(0, r - c);
};

int solve(vector<array<int, 3>> &vp, int s, int cur,
          vector<vector<int>> &memo) {
  if (s + 1 == (1 << vp.size())) {
    return dist(vp, cur, 0);
  } else if (memo[s][cur] < 0) {
    int ans = -1;
    for (int i = 0; i < vp.size(); ++i) {
      if (!(s & (1 << i))) {
        int a = solve(vp, s | (1 << i), i, memo) + dist(vp, cur, i);
        ans = ans < 0 || a < ans ? a : ans;
      }
    }

    memo[s][cur] = ans;
  }

  return memo[s][cur];
}

int main(int argc, const char *argv[]) {
  int n;
  cin >> n;
  vector<array<int, 3>> vp(n);
  for (int i = 0; i < n; ++i) {
    cin >> vp[i][0];
    cin >> vp[i][1];
    cin >> vp[i][2];
  }

  vector<vector<int>> memo(1 << n, vector<int>(n + 1, -1));
  int ans = solve(vp, 0, 0, memo);
  cout << ans << '\n';
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define V vector
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define mp make_pair
#define rep(i, n) for (int i = 0; i < (n); i++)
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()
#define sz(x) int(x.size())
#define pcnt __builtin_popcountll
template <typename T> bool chmin(T &a, const T &b) {if(a > b){a = b; return true;} return false;}
template <typename T> bool chmax(T &a, const T &b) {if(a < b){a = b; return true;} return false;}
template <typename T> void print(T a) {cout << a << ' ';}
template <typename T> void printe(T a) {cout << a << endl;}
template <typename T> void printv(T a) {rep(i, sz(a))print(a[i]); cout<<endl;}
template <typename T> void printp(pair<T, T> a) {print(a.first); cout<<a.second<<endl;}
template <typename A, size_t N, typename T> void Fill (A (&array)[N], const T & val) {fill ((T*)array, (T*)(array+N), val);}
template <typename T> using vc = vector<T>;
template <typename T> using vv = vc<vc<T>>;
template <typename T> using vvv = vc<vv<T>>;
using ll = long long;
using P = pair<int, int>;
using Pl = pair<ll, ll>;
using vi = vc<int>;
using vvi = vv<int>;
using vl = vc<ll>;
using vvl = vv<ll>;
vi di = {-1, 1,  0, 0, -1, -1,  1, 1};
vi dj = { 0, 0, -1, 1, -1,  1, -1, 1};

int main () {
    int n; cin >> n;
    vvl a(n, vl(5)); rep(i, n) rep(j, 5) cin >> a[i][j];
    ll ok = 0, ng = 1e10;
    while (abs(ok - ng) > 1) {
        ll mid = (ok + ng) / 2;
        vv<bool> flag(n, vc<bool>(5));
        rep(i, n) rep(j, 5) flag[i][j] = (a[i][j] >= mid);
        vi dp(1<<5, 10000);
        dp[0] = 0;
        rep(i, n) {
            rep(s, 1 << 5) {
                int t = s;
                rep(j, 5) if (flag[i][j]) t |= (1 << j);
                chmin(dp[t], dp[s] + 1);
            }
        }
        if (dp[(1<<5) - 1] <= 3) ok = mid;
        else ng = mid;
    }
    cout << ok << endl;
    return 0;
}

#include <algorithm>
#include <iostream>
#include <deque>
#include <climits>
#include <cmath>
#include <map>

using namespace std;

struct S {
    int left;
    int right;
};

int main() {
    int N;
    std::cin >> N;

    std::map<int, S> colors;
    for (int i = 0; i < N; i++) {
        int x, c;
        std::cin >> x >> c;
        if (colors.find(c) == colors.end()) {
            S s;
            s.left = x;
            s.right = x;
            colors[c] = s;
            continue;
        }
        if (x < colors[c].left) {
            colors[c].left = x;
        }
        if (x > colors[c].right) {
            colors[c].right = x;
        }
    }

    int left = 0;
    int64_t cleft = 0;
    int right = 0;
    int64_t cright = 0;

    for (auto pair : colors) {
        auto it = pair.second;
        // cout << pair.first << ' ' << it.left << ' ' << it.right << endl;
        int64_t cleft1 = cleft + abs(left - it.right) + abs(it.right - it.left);
        int64_t cleft2 = cright + abs(right - it.right) + abs(it.right - it.left);
        int64_t cright1 = cleft + abs(left - it.left) + abs(it.right - it.left);
        int64_t cright2 = cright + abs(right - it.left) + abs(it.right - it.left);
        cleft = cleft1 < cleft2 ? cleft1 : cleft2;
        cright = cright1 < cright2 ? cright1 : cright2;
        left = it.left;
        right = it.right;
    }

    cleft += abs(left);
    cright += abs(right);
    int64_t result = cleft < cright ? cleft : cright;

    std::cout << result << endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define vll vector<ll>
const int maxn = 1e6 + 5;
const int mod = 1e9 + 7;
int a[maxn];
int main()
{
    int n; cin >> n;
    double ans = 0;
    for (int i = 1 ; i < n ; i++){
        ans += 1.0 * n / i;
    }
    printf("%.10f\n" , ans);
    return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define MV 200001
#define LMV 21
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define emp emplace
#define mp make_pair
#define ins insert
#define sz(x) (int)x.size()
#define whoami(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); whi(_it, args); }

void whi(istream_iterator<string> it) { cerr<<"\n"; }

template<typename T, typename... Args>
void whi(istream_iterator<string> it, T a, Args... args) { cerr<<*it<<" "<<a<<" "; whi(++it, args...); }

void FLASH() {ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);}
void SETF() {cout.ios_base::setf(ios_base::fixed); cerr.ios_base::setf(ios_base::fixed);}
void UNSETF() {cout.ios_base::unsetf(ios_base::fixed); cerr.ios_base::unsetf(ios_base::fixed);}

typedef long long ll;
typedef long double ld;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef pair<PII, int> PPII;
typedef pair<PLL, ll> PPLL;
typedef map<int, int> MII;

const int MOD = 1000000007;
const ll INF = 4e18;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;

struct h_llint {
  static uint64_t splitmix64(uint64_t x) {    // http://xorshift.di.unimi.it/splitmix64.c
    x += 0x9e3779b97f4a7c15;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return x ^ (x >> 31);
  }
  size_t operator()(uint64_t x) const {
    static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
    return splitmix64(x + FIXED_RANDOM);
  }
};

struct h_pair{
  size_t operator()(const PLL&x)const{
    return hash<ll>()(((ll)x.ff)^(((ll)x.ss)<<32));
  }
};

typedef map<ll, ll> MLL;
typedef map<PII, int> MPII;
typedef map<PLL, ll> MPLL;
typedef set<int> SI;
typedef set<ll> SL;
//ordered_set = order_of_key(.)
//ordered_set = find_by_order(.)
typedef ordered_set<int> OSI;
typedef ordered_set<ll> OSL;
typedef ordered_multiset<int> MOSI;
typedef ordered_multiset<ll> MOSL;
typedef unordered_map<ll, int, h_llint> UMLI;
typedef unordered_map<ll, ll, h_llint> UMLL;
typedef unordered_map<PLL, int, h_pair> UMPI;
typedef unordered_map<PLL, ll, h_pair> UMPL;

int ar[MV];
ll arr[MV];

void solve(int T)
{
	ll n;
	cin>>n;
	ld rz = 0;
	for(int i=1;i<n;i++)
	rz += ((ld)n/(ld)i);
	SETF();
	cout<<setprecision(10)<<rz<<"\n";
	UNSETF();
	return;
}

int main(void)
{
	FLASH();
	//freopen("cowjog.in", "r", stdin);
	//freopen("cowjog.out", "w", stdout);
	int T;
	T = 1;

#ifndef ONLINE_JUDGE
	time_t time_t1, time_t2;
	time_t1 = clock();
#endif

	//cin>>T;
	while(T--)
	solve(T);

#ifndef ONLINE_JUDGE
	time_t2 = clock();
	SETF();
	cerr<<"Time taken: "<<setprecision(7)<<(time_t2 - time_t1)/(double)CLOCKS_PER_SEC<<"\n";
	UNSETF();
#endif

	return 0;
}


#include <bits/stdc++.h>
#define rep(a,n) for (ll a = 0; a < (n); ++a)
using namespace std;
//using namespace atcoder;
using ll = long long;
typedef pair<ll,ll> P;
typedef pair<ll,P> PP;
typedef vector<vector<int> > Graph;
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; }
const ll INF = 1e18;
#define SZ(x) ((int)(x).size())

#define debug(v) cout<<#v<<": ",prt(v);
template <typename A,typename B>
inline void prt(pair<A,B> p){cout<<"("<<p.first<<", "<<p.second<<")\n";}
template <typename A,typename B,typename C>
inline void prt(tuple<A,B,C> p){cout<<"("<<get<0>(p)<<", "<<get<1>(p)<<", "<<get<2>(p)<<")\n";}
inline void prt(bool p){if(p)cout<<"True"<<'\n';else cout<<"False"<<'\n';}
template <typename T>
inline void prt(vector<T> v){cout<<'{';for(ll i=0;i<v.size();i++){cout<<v[i];if(i<v.size()-1)cout<<", ";}cout<<'}'<<'\n';}
template<typename T>
inline void prt(vector<vector<T> >& vv){ for(const auto& v : vv){ prt(v); } }
template <typename T>
inline void prt(deque<T> v){cout<<'{';for(ll i=0;i<v.size();i++){cout<<v[i];if(i<v.size()-1)cout<<", ";}cout<<'}'<<'\n';}
template <typename A,typename B>
inline void prt(map<A,B> v){cout<<'{';ll c=0;for(auto &p: v){cout<<p.first<<":"<<p.second;c++;if(c!=v.size())cout<<", ";}cout<<'}'<<'\n';}
template <typename A,typename B>
inline void prt(unordered_map<A,B> v){cout<<'{';ll c=0;for(auto &p: v){cout<<p.first<<":"<<p.second;c++;if(c!=v.size())cout<<", ";}cout<<'}'<<'\n';}
template <typename T>
inline void prt(set<T> v){cout<<'{';for(auto i=v.begin();i!=v.end();i++){cout<<*i;if(i!=--v.end())cout<<", ";}cout<<'}'<<'\n';}
template <typename T>
inline void prt(multiset<T> v){cout<<'{';for(auto i=v.begin();i!=v.end();i++){cout<<*i;if(i!=--v.end())cout<<", ";}cout<<'}'<<'\n';}

/*
aはsortしておく
最後に残る可能性がある整数
a1~anのうちいずれかの約数(この時点で1つ以上のaの要素の公約数になることは確定する)
a１以下

上の条件を満たす整数を全列挙

kが最後に残るためにはaから取り出したいくつかの要素の最大公約数になることがあれば良い
これはaの要素のうちkの倍数のものをみていき、kで割った商の集合の最大公約数が1になれば良い

計算量
約数全列挙：O(N*(maxA)^1/2)
約数の個数の最大：2e6くらい?でも直感的にはもっと少なそう<-ダメだった

*/

/*  divisor(n)
    入力：整数 n
    出力：nのすべての約数
    計算量：O(√n)
*/

set<ll>st;
vector<ll>a;
map<ll,ll>mp;

void divisor(ll n){
    vector<ll>ret;
    for(ll i=1;i*i<=n;i++){
        if(n%i==0){
            ret.push_back(i);
            if(i*i!=n)ret.push_back(n/i);
        }
    }
	for(auto x:ret){
		if(x>a[0])continue;
		mp[x]=__gcd(mp[x],n);
		//st.insert(x);
	}
	return;
}

int main(){
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	ll n;
	cin >> n;
	a.resize(n);
	rep(i,n)cin>>a[i];
	sort(a.begin(),a.end());
	rep(i,n){
		divisor(a[i]);
		//debug(mp);
	}
	ll ans = 0;
	/*
	for(auto x:st){
		ll g = 0;//大丈夫かな？
		rep(i,n){
			if(a[i]%x==0){
				g = __gcd(a[i]/x,g);
			}
		}
		if(g==1)ans++;
	}
	*/
	for(auto p:mp){
		if(p.second==p.first)ans++;
	}
	cout << ans << endl;

	return 0;
}

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

void test(){
	int n; cin >> n;
	vector<int> a(n), b(n);
	map<int,int> mp;
	for(int &x:a)
		cin >> x;
	for(int &x:b)
		cin >> x;
	for(int i = 0; i < n; i++){
		for(int x = a[i]; x <= b[i]; x++){
			mp[x]++;
		}
	}
	int ans = 0;
	for(int i = 0; i <= 1000; i++){
		if(mp[i] == n){
			++ans;
		}
	}
	cout << ans;
}

signed main(){
    ios::sync_with_stdio(false);
    #ifndef ONLINE_JUDGE
    	freopen("input.txt", "r", stdin);freopen("answer.txt", "w", stdout);
	#endif
    int testcases = 1;
   // cin >> testcases;
    while(testcases-->0){
        test();
    }
}


//Let's join Kaede Takagaki Fan Club !!
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
#define fi first
#define sc second
#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())
#define all(x) x.begin(),x.end()
template<class T>
void dmp(T a){
	rep(i,a.size()) cout << a[i] << " ";
	cout << endl;
}
template<class T>
bool chmax(T&a, T b){
	if(a < b){
		a = b;
		return 1;
	}
	return 0;
}
template<class T>
bool chmin(T&a, T b){
	if(a > b){
		a = b;
		return 1;
	}
	return 0;
}
template<class T>
void g(T &a){
	cin >> a;
}
template<class T>
void o(const T &a,bool space=false){
	cout << a << (space?' ':'\n');
}
//ios::sync_with_stdio(false);
const ll mod = 1000000007;//998244353
template<class T>
void add(T&a,T b){
	a+=b;
	if(a >= mod) a-=mod;
}
int n;
ll a[200005];
int main(){
	cin >> n;
	rep(i, n) cin >> a[i];
	sort(a, a+n);
	ll ans = 0;
	rep(i, n-1){
		ans += 1LL*(i+1)*(n-1-i)*(a[i+1]-a[i]);
	}
	cout<<ans<<endl;}

//#undef DEBUG
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll llinf = (1ll<<61)-1;
#define sz(a) int(a.size())
#define all(x) begin(x), end(x)
#ifdef DEBUG
const int DEBUG_END = 26;
#define DOS cout
#include <debug.h>
#else
#define bug(args...) void()
#define cbug(a, args...)
#endif
#define ASSERT(a, o, b, args...) if (!((a)o(b))) bug(a, b, ##args), assert((a)o(b));
#define fi first
#define se second
const int inf = 1000000007, N=200005;
int TC = 1, CN, n, a[N];

signed main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); cout.precision(11), cout.setf(ios::fixed);
    //cin >> TC;// inputAll + resetAll -> solution
    auto kase = [&]()->void {
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
        }
        sort(a+1, a+1+n);
        ll ans = 0, ps = 0;
        for (int i = 1; i <= n; i++) {
            ans += ll(i-1)*a[i]-ps;
            ps += a[i];
        }
        cout << ans << '\n';
    };
    while (CN++!=TC) kase();
}


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

using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vc = vector<char>;
using vcc = vector<vc>;
using Pii = pair<int,int>;
using ld = long double;

#define rep(i,n) for(int i = 0; i<(int)n; i++)
#define per(i,n) for(int i = n-1; i>=0; i--)
#define mysort(V) sort(V.begin(),V.end())
#define myreverse(V) reverse(V.begin(),V.end())
#define myunique(V) V.erase( unique(V.begin(), V.end()), V.end() );
#define print(s) cout << s << endl;

const ld PI = 3.14159265358979;

long long powll(long long x, long long n){
    if(n == 0) return 1;
    else       return powll(x,n-1)*x;
}

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

int main(){
    int N;
    cin >> N;
    ll ans = 0;
    for(int i = 0; i<N; i++){
        ll a,b;
        cin >> a >> b;
        ans += b*(b+1)/2;
        ans -= (a-1)*a/2;
    }
    cout << ans << endl;
}

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

int main() {
  long N, A, B, Ans=0;
  cin >> N;
  rep(i, N){
    cin >> A >> B;
    if((B-A+1)%2==0) Ans+=(A+B)*((B-A+1)/2);
    else Ans+=(A+B)*((B-A+1)/2)+(A+B)/2;
  }
  cout << Ans << endl;
}


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

typedef long long ll;
typedef long double ld;
typedef pair<int, int> Pii;
typedef pair<int, ll> Pil;
typedef pair<ll, ll> Pll;
typedef pair<ll, int> Pli;
typedef vector < vector<ll> > Mat;
#define fi first
#define se second
const ll MOD = 1e9 + 7;
const ll MOD2 = 998244353;
const ll MOD3 = 1812447359;
const ll INF = 1ll << 62;
const double PI = 2 * asin(1);
void yes() {printf("yes\n");}
void no() {printf("no\n");}
void Yes() {printf("Yes\n");}
void No() {printf("No\n");}
void YES() {printf("YES\n");}
void NO() {printf("NO\n");}

ll Pow(ll A, ll N){
  if (N == 0) return 1;
  if (N % 2 == 0) return Pow(A * A % MOD, N / 2);
  else return Pow(A * A % MOD, N / 2) * A % MOD;
}

int H, W;
ll K;
char S[2005][2005];
ll cnt[2005][2005], ans[2005][2005];

int main(){
  cin >> H >> W;
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      cin >> S[i][j];
      if (S[i][j] == '.') K++;
    }
  }

  for (int i = 1; i <= H; i++){
    queue <int> que;
    int now = 0;
    for (int j = 1; j <= W + 1; j++){
      if (S[i][j] == '.') {
        now++; que.push(j);
      }
      else{
        while (!que.empty()){
          cnt[i][que.front()] += now;
          que.pop();
        }
        now = 0;
      }
    }
  }
  for (int j = 1; j <= W; j++){
    queue <int> que;
    int now = 0;
    for (int i = 1; i <= H + 1; i++){
      if (S[i][j] == '.') {
        now++; que.push(i);
      }
      else{
        while (!que.empty()){
          cnt[que.front()][j] += now - 1;
          que.pop();
        }
        now = 0;
      }
    }
  }

  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      if (S[i][j] != '.') continue;
      ans[i][j] = Pow(2, K) - Pow(2, K - cnt[i][j]);
      ans[i][j] %= MOD;
      if (ans[i][j] < 0) ans[i][j] += MOD;
    }
  }

  ll res = 0;
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      res += ans[i][j];
      res %= MOD;
    }
  }
  cout << res << endl;

  return 0;
}

#include <iostream>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#include <queue>
#include <map>

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

/*bool compare_function(const pair<int, int> a, const pair<int, int> b)
{
    return a.first < b.first;
}*/
// use case
//sort(V.begin(), V.end(), compare_function);

/*struct compare
{
    bool operator ()(const pair<int, int> &a, const pair<int, int> &b) {
    if (a.second-a.first==b.second-b.first)
    {
        return a.first>b.first;
    }
    return a.second-a.first < b.second-b.first;}
};
priority_queue <pair<int,int>, vector <pair<int,int>>, compare> Q;*/

/*void print1(vector <int> X)
{
    for (int i=0; i<X.size(); i++)
    {
        cout<<X[i]<<" ";
    }
    cout<<endl;
    return;
}

void print2(vector <vector <int>> X)
{
    for (int i=0; i<X.size(); i++)
    {
    for (int j=0;j<X[i].size();j++) {
        cout<<X[i][j]<<" ";}
    cout<<endl;}
    return;
}*/

void update(vector <vector <int>> &A, vector <vector <pii>> &B, int r, int c, int h, int w) {
	//cout<<r<<" "<<c<<" "<<h<<" "<<w<<endl;
	if (r==h-1) {
		B[r][c].first=B[r][c+1].second+A[r][c+1];
		B[r][c].second=B[r][c+1].first;
		//cout<<B[r][c].first<<endl;
		return;
		}
	if (c==w-1) {
		B[r][c].first=B[r+1][c].second+A[r+1][c];
		B[r][c].second=B[r+1][c].first;
		return;
		}
	int a=B[r+1][c].second+A[r+1][c]-B[r+1][c].first;
	int b=B[r][c+1].second+A[r][c+1]-B[r][c+1].first;
	if (a>b) {
		B[r][c].first=B[r+1][c].second+A[r+1][c];
		B[r][c].second=B[r+1][c].first;
		return;
		}
	B[r][c].first=B[r][c+1].second+A[r][c+1];
	B[r][c].second=B[r][c+1].first;
	return;
	}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int h,w;
    cin>>h>>w;
    vector <string> X(h);
    for (int i=0;i<h;i++) {cin>>X[i];}
    vector <vector <int>> A(h,vector <int>(w,1));
    for (int i=0;i<h;i++) {
		for (int j=0;j<w;j++) {
			if (X[i][j]=='-') {A[i][j]=-1;}
			//cout<<i<<" "<<j<<" "<<A[i][j]<<endl;
			}
		}
    vector <vector <pii>> B(h,vector <pii>(w,{0,0}));
    for (int r=h-1;r>=0;r--) {
		for (int c=w-1;c>=0;c--) {
			if (r<h-1 || c<w-1) {update(A,B,r,c,h,w);}
			//cout<<r<<" "<<c<<" "<<B[r][c].first<<" "<<B[r][c].second<<endl;
			}
		}
	int a=B[0][0].first-B[0][0].second;
	if (a>0) {cout<<"Takahashi"<<endl;}
	if (a==0) {cout<<"Draw"<<endl;}
	if (a<0) {cout<<"Aoki"<<endl;}
    return 0;
}


#include <iostream>
#include <iomanip>
#include <cctype>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
using namespace std;

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

    int n, count = 0; cin >> n;

    rep2(i, 1, n + 1){
    	int n10 = i;

    	while(n10 != 0){
    		if(n10 % 10 == 7) break;

    		n10 /= 10;
    	}

    	int n8 = i;

    	while(n8 != 0){
    		if(n8 % 8 == 7) break;

    		n8 /= 8;
    	}

    	if(n10 == 0 && n8 == 0) count++;
    }

    cout << count << "\n";

	return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(ll i = 0, i##_len = (n); i < i##_len; i++)
#define reps(i, s, n) for(ll i = (s), i##_len = (n); i < i##_len; i++)
#define rrep(i, n) for(ll i = (n) - 1; i >= 0; i--)
#define rreps(i, e, n) for(ll i = (n) - 1; i >= (e); i--)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) ((ll)(x).size())
#define len(x) ((ll)(x).length())
#define endl "\n"
template<class T> void chmax(T &a, const T b){ a = max(a, b); }
template<class T> void chmin(T &a, const T b){ a = min(a, b); }
long long gcd(long long a, long long b) { return (a % b) ? gcd(b, a % b) : b; }
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }

void solve() {
    ll l, r;
    cin >> l >> r;
    ll val = r - 2 * l + 1;
    ll ans = ((val > 0) ? (1 + val) * val / 2 : 0);
    cout << ans << endl;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    // ifstream in("input.txt");
    // cin.rdbuf(in.rdbuf());
    ll t;
    cin >> t;
    rep(i, t) solve();
    return 0;
}


#include <iostream>
using namespace std;
int main(void){
    // Your code here!
    int n;
    cin >> n;
    if(n % 2 == 0){
        cout << "White" << endl;
    }
    else{
        cout << "Black" << endl;
    }
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// oset Operations: order_of_key(k) -> Number of elements strictly smaller than k, find_by_order(k) -> kth element in the set

#define ull unsigned long long int
#define ll long long int
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(),x.end()
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vb vector<bool>
#define vd vector<double>
#define vll vector<ll>
#define vpii vector<pii>
#define vpll vector<pll>
#define vvi vector<vi>
#define vvll vector<vll>
#define vvb vector<vb>
#define vs vector<string>
#define pull pair<ull, ull>
#define F first
#define S second
#define m_p make_pair

const long double PI = 3.141592653589793238462643383279502884197169399;

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);
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.push_back(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)) + ")";
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}
#ifndef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 0
#endif

// Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))

const int mod = 1e9+7;

void solve(){
	int n;
	cin >> n;

	cout << (n&1 ? "Black" : "White");
}

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

	cout << fixed << setprecision(10);

	int tt=1;
//	cin >> tt;

	while(tt--){
		solve();
	}
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rrep(i,n) for (int i = (int)(n)-1; i>=0; --i)
#define For(i,a,b) for(auto i=(a);i<=(b);++i)
#define rFor(i,a,b) for(auto i=(b);i>=(a);--i)
#define call(var) cerr<<#var<<"="<<var<<"\n";
#define dup(x,y) (((x)+(y)-1)/(y))
#define all(x) (x).begin(),(x).end()
using ll=long long;
using vi = vector<int>;
using vl = vector<ll>;
using vb = vector<bool>;
using Graph = vector<vi>;
using P = pair<int,int>;
const int MOD=(int)1e9+7;
const int INF=(int)1e9;
const ll LINF=(ll)1e18;
const double pi = acos(-1);
template<class t,class u> inline bool chmax(t&a,u b){if(a<b){a=b;return true;}return false;}
template<class t,class u> inline bool chmin(t&a,u b){if(b<a){a=b;return true;}return false;}
template<class T> istream& operator>>(istream& is, vector<T>& a){rep(i,a.size()) is >> a[i]; return is;}
template<class T> ostream& operator<<(ostream& os, vector<T>& a){rep(i,a.size()) os << a[i] << " "; return os;}
template<class T, class U> istream& operator>>(istream& is, pair<T,U>& p){is >> p.first >> p.second; return is;}
template<class T, class U> ostream& operator<<(ostream& os, const pair<T,U>& p){os << "("<< p.first << "," << p.second << ")"; return os;}
template<class T, class U> ostream& operator<<(ostream& os, const map<T,U>& mp){for(auto& t : mp) os << t.first << " " << t.second << "\n"; return os;}

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

    int ma = 0, ans = a[0];
    for(int i=2;i<=1000;i++){
        int cnt = 0;
        rep(j,n){
            if(a[j]%i == 0) ++cnt;
        }
        if(ma < cnt){
            ma = cnt;
            ans = i;
        }
    }
    cout << ans << endl;
}

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
int main(){
  int n;
  cin>>n;
  vector<int> a(n);
  for(int i=0;i<n;i++){
    cin>>a[i];
  }
  int ans=2;
  int max=0;
  for(int i=2;i<=1000;i++){
    int counter=0;
    for(int j=0;j<n;j++){
      if(a[j]%i==0){
        counter++;
      }
    }
    if(max<counter){
      max=counter;
      ans=i;
    }
  }
  cout<<ans<<endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long int
#define mod 1000000007
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);

int main() {
    FIO;
    int t,n,i,j;
    cin>>n;
    int x[n];
    int y[n];
    for(i=0;i<n;i++){
        cin>>x[i]>>y[i];
    }
    int cnt=0;
    for(i=0;i<n-1;i++){
        for(j=i+1;j<n;j++){
            float slope = (float)(y[j]-y[i])/(float)(x[j]-x[i]);
            if(slope>=-1 && slope<=1)
                cnt++;
        }
    }

    cout<<cnt;

    return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++)
#define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--)
#define REP(i, n) FOR(i, 0, (n)-1)
#define sqr(x) ((x) * (x))
#define all(x) (x).begin(), (x).end()
#define reset(x, y) memset(x, y, sizeof(x))
#define uni(x) (x).erase(unique(all(x)), (x).end())
#define BUG(x) cerr << #x << " = " << (x) << endl
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define _1 first
#define _2 second
#define chkmin(a, b) a = min(a, b)
#define chkmax(a, b) a = max(a, b)

const int maxn = 212345;

int h, w, m;
int reach[maxn], fen[maxn];
bool vis[maxn];
vector<int> G[maxn];

void add(int x, int v) {
  while (x <= w) {
    fen[x] += v;
    x += x & -x;
  }
}

int query(int x) {
  int ret = 0;
  while (x > 0) {
    ret += fen[x];
    x -= x & -x;
  }
  return ret;
}

int main() {
#ifdef ONLINE_JUDGE
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
#endif
  cin >> h >> w;
  FOR(i, 1, h) reach[i] = w;
  cin >> m;
  while (m--) {
    int x, y; cin >> x >> y;
    G[x].eb(y);
    chkmin(reach[x], y - 1);
  }
  ll ans = 0;
  bool f = true;
  ans += reach[1];
  FOR(i, 1, reach[1]) add(i, 1), vis[i] = true;
  FOR(i, 2, h) {
    for (auto y : G[i]) if (vis[y]) {
      add(y, -1);
      vis[y] = false;
    }
    if (!vis[1]) f = false;
    ans += reach[i] * f + query(w) - query(f ? reach[i] : 0);
  }
  cout << ans;
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vl = vector<ll>;
#define rep(i,n) for(int i=0;i<(n);i++)
#define rrep(i,n) for(int i=(n)-1;i>=0;i--)
#define rep1(i,n) for(int i=1;i<=(n);i++)
#define rrep1(i,n) for(int i=(n);i>0;i--)
#define fore(i_in,a) for (auto& i_in: a)
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define cnts(x,c) count(all(x),c)
#define fio() cin.tie(nullptr);ios::sync_with_stdio(false);
#define DEBUG_CTN(v) cerr<<#v<<":";for(auto itr=v.begin();itr!=v.end();itr++) cerr<<" "<<*itr; cerr<<endl
template<class T> bool chmax(T &a, const T &b) {if (a<b) {a = b; return 1;} return 0;}
template<class T> bool chmin(T &a, const T &b) {if (a>b) {a = b; return 1;} return 0;}
template<class T> void print(const T &t) {cout << t << "\n";}
const ll INF = 1LL << 62;
const int iINF = 1 << 30;

ll n,m,k;

int main() {
    fio(); cin>>k>>n>>m;
    vl a(k),c(k); fore(x,a) cin>>x;
    vector<pair<ll,int>> b;
    rep(i,k) {
        c[i]=a[i]*m/n;
        b.emplace_back(c[i]*n-a[i]*m,i);
    }
    sort(all(b));
    ll tmp=0;
    fore(x,c) tmp+=x;
    ll res=m-tmp;
    rep(i,res) {
        auto j=b[i].second;
        c[j]++;
    }
    rep(i,k) cout<<c[i]<<" \n"[i==k-1];
}

#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<iomanip>
#include<algorithm>
#include<cmath>
#include<bitset>
#include<queue>
#include<stack>
#include<utility>
#include<cstdlib>
#include<cstdio>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<list>
#include<tuple>
using namespace std;

typedef long long ll;
typedef long double ld;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvl;

typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;

#define FOR(i, a, b) for(ll i=(a); i<(b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define NREP(i, n) FOR(i, 1, n+1)

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

struct Edge{
    ll to, cost;
    Edge(ll t, ll c) : to(t), cost(c) { }
};
using Graph = vector<vector<Edge>>;

ll MODpow(ll x, ll n, ll mod){
	ll res=1;
	while(n>0){
		if(n&1) res=res*x%mod;
		x=x*x%mod;
		n >>= 1;
	}
	return res;
}

const ll MOD=1e9+7;
const ll nmax=200000+10;

ll N;
ll color[nmax][60];
ll cnt1[60];
ll seen[nmax];

Graph G(nmax);
ll solve(){
    queue<ll> q;
    q.push(0);
	REP(i,60) color[0][i]=0;

    while(!q.empty()){
        ll v=q.front();
        q.pop();
        seen[v]=1;

        for(auto e:G[v]){
            if(seen[e.to]) continue;

			ll et=e.to, ec=e.cost;
			q.push(e.to);
			REP(i,60){
				bool eci=ec&1;
				ec>>=1;
				color[et][i]=color[v][i]^eci;
				if(color[et][i]) cnt1[i]++;
			}
        }
    }

	ll res=0,rec=1;
	REP(i,60){
		ll mid1=rec;
		rec=rec*2%MOD;
		ll mid2=(N-cnt1[i])*cnt1[i]%MOD;
		ll mid=mid1*mid2%MOD;
		res+=mid;
		res%=MOD;
	}

    return res;
}

int main(void){
    cin>>N;
    REP(i,N-1){
        ll u,v,w; cin>>u>>v>>w;
        u--,v--;
        G[u].push_back(Edge{v,w});
        G[v].push_back(Edge{u,w});
    }

    ll res=solve();
    cout<<res<<endl;

    return 0;
}


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

typedef long long ll;
typedef unsigned long long ull;
typedef double dbl;
typedef float flt;

#define for0(i, n) for(ll i=0; i<n; i++)
#define for1(i, n) for(ll i=1; i<=n; i++)
#define forab(i, a, b) for(ll i=a; i<=b; i++)
#define clr0(a) memset(a, 0, sizeof(a))

void solve() {
    ll a, b;
    cin >> a >> b;
    if (a+b>=15 && b>=8) {
        cout << 1 << endl;
    }
    else if (a+b>=10 && b>=3) {
        cout << 2 << endl;
    }
    else if (a+b>=3) {
        cout << 3 << endl;
    }
    else {
        cout << 4 << endl;
    }
}

void testcase() {
    ll t;
    cin >> t;
    while (t--) {
        solve();
    }
}

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

    //testcase();
    solve();

    return 0;
}

#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;

int main() {
  int a , b ;
  cin >> a >> b ;
  if((a+b)>=15 && b>=8)
  {
      cout << 1 ; /// "ice cream";
      return 0;
  }
  if((a+b)>=10 && b>=3)
  {
      cout << 2 ; /// "1 ice milk";
      return 0;
  }
  if((a+b)>=3)
  {
      cout << 3 ; // "lacto milk";
      return 0;
  }
  cout << 4 ; /// "flavored ice";
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define R cin>>
#define ll long long
#define ln cout<<'\n'
#define in(a) insert(a)
#define pb(a) push_back(a)
#define pd(a) printf("%.10f\n",a)
#define mem(a) memset(a,0,sizeof(a))
#define all(c) (c).begin(),(c).end()
#define iter(c) __typeof((c).begin())
#define rrep(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
#define rep(i,n) REP(i,0,n)
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
ll check(ll n,ll m,ll x,ll y){return x>=0&&x<n&&y>=0&&y<m;}void pr(){ln;}
template<class A,class...B>void pr(const A &a,const B&...b){cout<<a<<(sizeof...(b)?" ":"");pr(b...);}
template<class A>void PR(A a,ll n){rep(i,n)cout<<(i?" ":"")<<a[i];ln;}
const ll MAX=998244353,MAXL=1LL<<61,dx[8]={-1,0,1,0,-1,-1,1,1},dy[8]={0,1,0,-1,-1,1,1,-1};
typedef pair<ll,ll> P;

int p[200001],r[200001];
void init(){rep(i,200001)p[i]=i,r[i]=0;}
int find(int x){return (p[x]==x)?x:(p[x]=find(p[x]));}
void unite(int x,int y) {
  x=find(x),y=find(y);
  if(x==y)return;
  if(r[x]<r[y])p[x]=y;
  else{p[y]=x;if(r[x]==r[y])r[x]++;}
}
bool same(int x,int y){return find(x)==find(y);}

void Main() {
  ll n,m;
  cin >> n >> m;
  ll a[n][n];
  rep(i,n)rep(j,n) R a[i][j];
  ll d[n+1];
  mem(d);
  d[0]=1;
  REP(i,1,n+1) d[i]=d[i-1]*i%MAX;
  init();
  rep(i,n) {
    REP(j,i+1,n) {
      ll f1=1,f2=1;
      rep(k,n) {
        if(a[k][i]+a[k][j]>m) f1=0;
        if(a[i][k]+a[j][k]>m) f2=0;
      }
      if(f1) unite(i,j);
      if(f2) unite(i+n,j+n);
    }
  }
  ll x[n],y[n];
  mem(x);mem(y);
  rep(i,n) {
    x[find(i)]++;
    y[find(i+n)-n]++;
  }
  ll d1=1,d2=1;
  rep(i,n) {
    d1*=d[x[i]];
    d1%=MAX;
    d2*=d[y[i]];
    d2%=MAX;
  }
  pr(d1*d2%MAX);
}

int main(){ios::sync_with_stdio(0);cin.tie(0);Main();return 0;}

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

#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<long long,long long>
#define pb push_back
#define debug(x) cerr<<#x<<"="<<x<<endl
#define pq priority_queue
#define inf 0x3f
#define rep(i,a,b) for (int i=a;i<(b);i++)
#define MP make_pair
#define SZ(x) (int(x.size()))
#define ll long long
#define mod 1000000007
#define ALL(x) x.begin(),x.end()
void inc(int &a,int b) {a=(a+b)%mod;}
void dec(int &a,int b) {a=(a-b+mod)%mod;}
int lowbit(int x) {return x&(-x);}
ll p0w(ll base,ll p) {ll ret=1;while(p>0){if (p%2ll==1ll) ret=ret*base%mod;base=base*base%mod;p/=2ll;}return ret;}

const int maxn=110;

int n,m;
bool ans[maxn][maxn];
vector <int> edge[maxn];
pii e[maxn*maxn];
int c[maxn];
bool vis[maxn];

void dfs(int u) {
	vis[u]=true;
	for(int v:edge[u]) {
		if (ans[u][v]||ans[v][u]) continue;
		ans[u][v]=true;
		if (!vis[v])dfs(v);
	}
}

int main() {
//	freopen("input.txt","r",stdin);
	std::ios::sync_with_stdio(false);cin.tie();
	cin>>n>>m;
	rep(i,0,m) cin>>e[i].fi>>e[i].se;
	rep(i,1,n+1) cin>>c[i];
	memset(ans,0,sizeof(ans));
	rep(i,0,m) {
		if (c[e[i].fi]==c[e[i].se]) edge[e[i].fi].pb(e[i].se),edge[e[i].se].pb(e[i].fi);
		else if (c[e[i].fi]>c[e[i].se]) ans[e[i].fi][e[i].se]=true;
		else ans[e[i].se][e[i].fi]=true;
	}
	rep(i,1,n+1) dfs(i);
	rep(i,0,m) {
		if (ans[e[i].fi][e[i].se]) cout<<"->\n";
		else cout<<"<-\n";
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int power(long long int x,long long int y,long long int p)
{
    int res = 1;

    x = x % p;
    if (x == 0) return 0;

    while (y > 0)
    {
        if (y & 1)
            res = (res*x) % p;
        y = y>>1;
        x = (x*x) % p;
    }
    return res;
}
int main(){
	ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t=1;
    //cin>>t;
    while(t--){
       int n;
       cin>>n;
       string s;
       set<string> st;
       string ans="satisfiable";
       for(int i=0;i<n;i++){
       	 cin>>s;
       	 reverse(s.begin(),s.end());
       	 string search,temp=s;
       	 if(s[s.size()-1]=='!'){
       	 	s.pop_back();
       	 	if(st.find(s)!=st.end()&&ans=="satisfiable"){
       	 	  	reverse(s.begin(),s.end());
       	 	  	ans=s;
			}
		 }
		 else{
		 	s+='!';
		 	if(st.find(s)!=st.end()&&ans=="satisfiable"){
       	 	  	reverse(temp.begin(),temp.end());
       	 	  	ans=temp;
       	 	  	reverse(temp.begin(),temp.end());
			}
		 }
		 st.insert(temp);
	   }
	   cout<<ans<<"\n";
    }
	return 0;
}

#include<stdio.h>
#include<iostream>
#include<vector>
#include<math.h>
#include<queue>
#include<map>
#include<algorithm>
#include<string.h>
#include<functional>
#include<limits.h>
#include<stdlib.h>
#include<string>
#include<unordered_map>
#include <iomanip>
using namespace std;

#define intmax INT_MAX
#define lmax LONG_MAX
#define uintmax UINT_MAX
#define ulmax ULONG_MAX
#define llmax LLONG_MAX
#define ll long long
#define rep(i,a,N) for((i)=(a);(i)<(N);(i)++)
#define rrp(i,N,a) for((i)=(N)-1;(i)>=(a);(i)--)
#define llfor ll i,j,k
#define sc(a) cin>>a
#define pr(a) cout<<a<<endl
#define pY puts("YES")
#define pN puts("NO")
#define py puts("Yes")
#define pn puts("No")
#define pnn printf("\n")
#define sort(a) sort(a.begin(),a.end())
#define reverse(a) reverse(a.begin(),a.end())
#define push(a,b) (a).push_back(b)
#define llvec vector<vector<ll>>
#define charvec vector<vector<char>>
#define sizeoof(a,b) (a,vector<ll>(b))
#define llpvec vector<pair<ll,ll>>
/*繰り上げ除算*/ll cei(ll x,ll y){ll ans=x/y;if(x%y!=0)ans++;return ans;}
/*最大公約数*/ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*最小公倍数*/ll lcm(ll x,ll y){return x/gcd(x,y)*y;}
/*n乗*/ll llpow(ll x,ll n){ll i,ans=1;rep(i,0,n)ans*=x;return ans;}
/*階乗*/ll fact(ll x){ll i,ans=1;rep(i,0,x)ans*=(x-i);return ans;}
/*nCr*/ll ncr(ll n,ll r){return fact(n)/fact(r)/fact(n-r);}
/*nPr*/ll npr(ll n,ll r){return fact(n)/fact(n-r);}
/*primejudge*/bool prime(ll a){if(a<=1)return false;ll i;for(i=2;i*i<=a;i++){if(a%i==0)return false;}return true;}
ll ans=0;llfor;///////////////////////////////////////////////////////////
int main(){
  ll N;
  cin>>N;
  ll ans=0;
  if(N>=1000) ans+=N-999;
  if(N>=1000000) ans+=N-999999;
  if(N>=1000000000) ans+=N-999999999;
  if(N>=1000000000000) ans+=N-999999999999;
  if(N>=1000000000000000) ans+=N-999999999999999;
  cout<<ans<<endl;
return 0;}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define mp make_pair
#define pb push_back
#define pll pair<ll,ll>

#define deb1(a) cout<<#a<<" = "<<(a)<<endl;
#define deb2(a,b) cout<<#a<<" = "<<(a)<<", "<<#b<<" = "<<(b)<<endl;
#define deb3(a,b,c) cout<<#a<<" = "<<(a)<<", "<<#b<<" = "<<(b)<<", "<<#c<<" = "<<(c)<<endl;

ll INF = 1000000007;

//-----------------//
  #define amin main
//-----------------//

ll dp[1005][1005];
ll arr[1005];
ll brr[1005];

ll solve(ll i,ll j)
{

	if(dp[i][j]!=-1)
	return dp[i][j];
	if(i==0 || j==0)
		return max(i,j);

	return dp[i][j] = min(solve(i-1,j)+1,min(solve(i,j-1)+1,solve(i-1,j-1) + ((ll)(arr[i]!=brr[j]))));
}

int amin()
{
	 	// freopen("input.txt", "r", stdin);
  		// freopen("output.txt", "w", stdout);
		ios_base::sync_with_stdio(false);
		cin.tie(NULL);
		ll t,i,j;
		ll n,m;
		cin>>n>>m;
		for(i=1;i<=n;i++)
			cin>>arr[i];
		for(j=1;j<=m;j++)
			cin>>brr[j];
		for(i=0;i<=n;i++)
		{
			for(j=0;j<=m;j++)
				dp[i][j]=-1;
		}
		cout<<solve(n,m)<<endl;

	return 0;
}

// *********************************************************************************
// *                        MURTAZA MUSTAFA KHUMUSI                                *
// *                        NIT-DGP,CSE - 2019-2023                                *
// *********************************************************************************

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MOD 1000000007;
#define loop(i, a, n) for (int i = a; i < n; i++)
#define loop1(i, b, n) for (int i = b; i <= n; i++)
#define loopit(a) for (auto it = a.begin(); it != a.end(); it++)
#define ms(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define MP make_pair
#define pi pair<int, int>
#define ff first
#define ss second
#define bloop(i, a, b) for (int i = a; i > b; i--)
#define bloop1(i, a, b) for (int i = a; i >= b; i--)
#define PQ priority_queue<int> pq;
#define vi vector<int>
#define si set<int>
#define MPQ priority_queue<pi, vector<int>, greater<pi>> mpq;
#define io                        \
    ios_base::sync_with_stdio(0); \
    cin.tie(NULL);                \
    cout.tie(NULL);
const int maxm = 100001;

// ll m = 1e9+7;
ll m = 998244353;
vector<vi> adj;
vi h, sz, in;
vector<ll> fact;

//modular arithmentic

ll add(ll a, ll b, ll mod = m)
{
    return ((a % mod) + (b % mod)) % mod;
}
ll mul(ll a, ll b, ll mod = m)
{
    return ((a % mod) * (b % mod)) % mod;
}
ll sub(ll a, ll b, ll mod = m)
{
    return ((a % mod) - (b % mod) + mod) % mod;
}

ll modmul(ll a, ll b, ll mod = m)
{
    ll ans = 0;
    a = a % mod;
    while (b)
    {
        if (b & 1)
            ans = add(ans, a, mod);
        a = mul(a, 2, mod);
        b >>= 1;
    }
    return ans;
}

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

ll fe(ll base, ll exp, ll mod = m)
{
    ll ans = 1;
    while (exp)
    {
        if (exp & 1)
            ans = mul(ans, base, mod);
        base = mul(base, base, mod);
        exp >>= 1;
    }
    return ans;
}

ll modin(ll a, ll mod = m)
{
    return fe(a, mod - 2, mod);
}

ll nCr(ll a, ll b, ll mod = m)
{
    if (a < b)
        return 0;
    return mul(fact[a], mul(modin(fact[b], mod), modin(fact[a - b], mod)));
}

//graph theory
void dfs_h_sz(int cur, int par)
{
    h[cur] = h[par] + 1;
    sz[cur]++;
    for (const auto &v : adj[cur])
    {
        if (v == par)
            continue;
        dfs_h_sz(v, cur);
        sz[cur] += sz[v];
    }
}

void buildGraph(int n, int m)
{
    adj = vector<vi>(n + 1);
    h = vector<int>(n + 1);
    sz = vector<int>(n + 1);
    in = vector<int>(n + 1);

    loop(i, 0, m)
    {
        int a, b;
        cin >> a >> b;
        adj[a].pb(b);
        adj[b].pb(a);
    }
    dfs_h_sz(1, 0);
}
struct cmp
{
    bool operator()(const pi &a, const pi &b)
    {
        return a.ff < b.ff;
    }
};

void solve()
{
    int n,m;
    cin>>n>>m;
    int dp[n+1][m+1];
    int in1[n+1],in2[m+1];
    loop1(i,1,n)cin>>in1[i];

    loop1(i,1,m)cin>>in2[i];

    loop1(i,0,n){
        loop1(j,0,m){
            if(i==0)
            dp[i][j] = j;
            else if(j==0)
            dp[i][j] = i;
            else
            dp[i][j] = min(dp[i][j-1]+1,min(dp[i-1][j]+1,dp[i-1][j-1]+(in1[i]!=in2[j])));
        }
    }
    cout<<dp[n][m]<<"\n";
}
int main()
{
    io;
// #ifndef ONLINE_JUDGE
//     freopen("input.txt", "r", stdin);
//     freopen("output.txt", "w", stdout);
// #endif
    int test;
    // cin >> test;
    test=1;
    while (test--)
    {
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
#define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i)
#define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i)
#define foreach(i, n) for(auto &i:(n))
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
#define lambda(RES_TYPE, ...) (function<RES_TYPE(__VA_ARGS__)>)[&](__VA_ARGS__) -> RES_TYPE
#define method(FUNC_NAME, RES_TYPE, ...) function<RES_TYPE(__VA_ARGS__)> FUNC_NAME = lambda(RES_TYPE, __VA_ARGS__)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
//const ll MOD = (ll)1e9+7;
const ll MOD = 998244353;
const int INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
template<class t>
using vvector = vector<vector<t>>;
template<class t>
using vvvector = vector<vector<vector<t>>>;
template<class t>
using priority_queuer = priority_queue<t, vector<t>, greater<t>>;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}
#ifdef DEBUG
#define debug(x) cout<<"LINE "<<__LINE__<<": "<<#x<<" = "<<x<<endl;
#else
#define debug(x) (void)0
#endif

namespace templates{
  ll modpow(ll x, ll b){
    ll res = 1;
    while(b){
      if(b&1)res = res * x % MOD;
      x = x * x % MOD;
      b>>=1;
    }
    return res;
  }

  ll modinv(ll x){
    return modpow(x, MOD-2);
  }

  bool was_output = false;
  template<class t>
  void output(t a){
    if(was_output)cout << " ";
    cout << a;
    was_output = true;
  }
  void outendl(){
    was_output = false;
    cout << endl;
  }
  ll in(){
    ll res;
    scanf("%lld", &res);
    return res;
  }

  template<class t>
  istream& operator>>(istream&is, vector<t>&x){
    for(auto &i:x)is >> i;
    return is;
  }

  template<class t, class u>
  istream& operator>>(istream&is, pair<t, u>&x){
    is >> x.first >> x.second;
    return is;
  }

  template<class t>
  t in(){
    t res; cin >> res; return res;
  }

  template<class t>
  void out(t x){
    cout << x;
  }

  template<class t>
  vector<t> sorted(vector<t> line,function<bool(t,t)> comp=[](t a,t b){return a<b;}){
    sort(line.begin(),line.end(),comp);
    return line;
  }

  template<class t>
  vector<t> reversed(vector<t> line){
    reverse(line.begin(),line.end());
    return line;
  }
}

using namespace templates;

ll func(){
    int n = in();
    int L = in();
    vector<ll> start(n);
    vector<ll> goal(n);
    foreach(i,start)i=in();
    foreach(i,goal)i=in();
    vector<ll> x(n+1);
    vector<ll> y(n+1);
    x[0] = start[0]-1;
    y[0] = goal[0]-1;
    x.back() = L - start.back();
    y.back() = L - goal.back();
    rep(i,1,n){
        x[i] = start[i]-start[i-1]-1;
        y[i] = goal[i]-goal[i-1]-1;
    }
    int last = 0;
    ll res = 0;
    rep(i,n+1){
        while(last < n + 1 and x[last]==0)++last;
        if(y[i]==0)continue;
        ll sum = 0;
        int itr = last;
        while(sum < y[i]){
            sum += x[itr++];
        }
        if(sum != y[i])return -1;
        if(last < i and i < itr){
            res += i - last;
            res += itr - i - 1;
        }else{
            res += max(abs(i-last),abs(i-(itr-1)));
        }
        last = itr;
    }
    return res;
}

int main(){
    cout << func() << endl;
  return 0;
}

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

#define MAX 1000000010
using ll = long long;

int main(){
    ll N, C;
    cin >> N >> C;

    vector<pair<ll,ll>>event;

	for(int i=0;i<N;i++){
        ll a, b, c;
        cin >> a >> b >> c;
		event.push_back(make_pair(a,c));
		event.push_back(make_pair(b+1,-c));
	}

	sort(event.begin(), event.end());

	ll cost = 0;
    ll ans = 0;
    ll beforeday = 0;
    ll beforecost = 0;

    for(auto day : event){
        ans += beforecost * (day.first - beforeday);
        cost += day.second;
        beforecost = min(cost, C);
        beforeday = day.first;
    }

    cout << ans;
}


#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2,fma,tune=native")

#define ll long long
#define int ll
#define ull unsigned ll
#define ld long double
#define rep(a) rep1(i,a)
#define rep1(i,a) rep2(i,0,a)
#define rep2(i,b,a) for(int i=(b); i<((int)(a)); i++)
#define rep3(i,b,a) for(int i=(b); i>=((int)(a)); i--)
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define pb push_back
//#define inf 1010000000
#define inf 4000000000000000000
#define eps 1e-9
#define sz(a) ((int)a.size())
#define pow2(x) (1ll<<(x))
#define ceiling(a,b) (((a)+(b)-1)/(b))
#define print0(a) cout << (a) << ' '
#define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#ifdef i_am_noob
#define bug(...) cerr << "#" << __LINE__ << ' ' << #__VA_ARGS__ << "- ", _do(__VA_ARGS__)
template<typename T> void _do(vector<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";}
template<typename T> void _do(set<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";}
template<typename T> void _do(T && x) {cerr << x << endl;}
template<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << ", "; _do(y...);}
#else
#define bug(...) 826
#endif
template<typename T> void print(T && x) {cout << x << "\n";}
template<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);}

const int Mod=1000000007,Mod2=998244353;
const int MOD=Mod2;
const int maxn=200005;

//i_am_noob
//#define wiwihorz
int n,a[maxn],b[maxn],c[4];
bool vis[maxn];

void orzck(){
    cin >> n;
    rep(n) cin >> a[i] >> b[i];
    c[0]=min_element(a,a+n)-a;
    c[1]=max_element(a,a+n)-a;
    c[2]=min_element(b,b+n)-b;
    c[3]=max_element(b,b+n)-b;
    vector<int> vec;
    rep1(j,4){
        vis[c[j]]=1;
        rep(n) if(!vis[i]) vec.pb(max(abs(a[i]-a[c[j]]),abs(b[i]-b[c[j]])));
    }
    sort(all(vec));
    print(vec[sz(vec)-2]);
}

signed main(){
    ios_base::sync_with_stdio(0),cin.tie(0);
    #ifdef i_am_noob
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
    freopen("output2.txt","w",stderr);
    #endif
    cout << fixed << setprecision(15);
    int t;
    #ifdef wiwihorz
    cin >> t;
    #else
    t=1;
    #endif
    while(t--) orzck();
    return 0;
}

#include<bits/stdc++.h>
#include<iostream>
#include<set>
#include<map>
#include<iterator>
using namespace std;

///defines.....
#define ll              long long
#define lli             long long int
#define pb              push_back
#define mp              make_pair
#define RIP(i,n)        for(ll i=0; i<n; i++)
#define F(i,a,b)        for(int i=a; i<b; i++)
#define RIP1(i,n)       for(int i=(n-1); i>=0; i--)
#define FOR(i,a,b)      for(int i=a;i<(b); i++)
#define FOR1(i,a,b)     for(int i=a; i>=(b); i--)
#define sc(a)           scanf("%lld",&a)
#define SC(a)           scanf("%d",&a)
#define cin(a)          cin >> a
#define cout(a)         cout << a
#define pi              acos(-1)
#define pr(a)           printf("%lld\n",a)
#define PR(a)           printf("%lld ",a)
#define s(a,b)          sort(a,b)
#define sz(x)           (int)(x).size()
#define nl              '\n'

///Constants........
const ll mod = 1e9+7;
const int Max = 1e5+5;
const ll IFN = 1e18+5;

///Chess moves.........
 int dx[] = {+0, +0, -1, +1}; ///Up-down, Left-Right
 int dy[] = {+1, -1, +0, +0};
// int dx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's Move
// int dy[] = {-1,+1,+0,+0,+1,+1,-1,-1};
// int dx[] = {-2, -2, -1, -1,  1,  1,  2,  2}; ///Knight's Move
// int dy[] = {-1,  1, -2,  2, -2,  2, -1,  1};

inline void norm(ll &a) {a%=mod; (a<0) && (a+=mod) ;}
inline ll modAdd(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a+b)%mod;}
inline ll modSub(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a-b)%mod;}
inline ll modMul(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a*b)%mod;}

///Functions..........
ll bigmod(ll a, ll p, ll M)
{
	p %= (M-1);

	ll result = 1LL;
	while(p>0LL){
		if(p&1LL) result = result * a % M;
		a = a * a % M;
		p>>=1LL;
	}
	return result;
}

ll gcd(ll a, ll b){ while (b){ a %= b; swap(a, b);} return a;}
ll lcm(ll a, ll b){ return (a/gcd(a, b)*b);}

ll inverse(ll a, ll M){
	if(gcd(a, M)==1) return bigmod(a, M-2, M) % M;
	return 1;
}
ll ncr(ll a, ll b){ ll x = max(a-b, b), ans=1; for(ll K=a, L=1; K>=x+1; K--, L++){ ans = ans * K % mod; ans = ans * inverse(L, mod) % mod;} return ans;}

void F_I_O()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}

/* void solve()
{

}*/

/// Code goes from here ::::::>

int main()
{

    /*#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif*/

    int t=1;
    //cin >> t;
    while(t--)
    {
        ll n;
        cin >> n;
        vector<pair<ll,ll>>v1,v2;
        ll a,b;
        RIP(i,n)
        {
            cin >> a >> b;
            v1.pb({a,i});
            v2.pb({b,i});
        }
        sort(v1.begin(),v1.end());
        sort(v2.begin(),v2.end());
        vector<pair<ll,pair<ll,ll>>>v;
        v.pb({abs(v1[n-1].first-v1[0].first),{v1[n-1].second,v1[0].second}});
         v.pb({abs(v1[n-1].first-v1[1].first),{v1[n-1].second,v1[1].second}});
          v.pb({abs(v1[n-2].first-v1[0].first),{v1[n-2].second,v1[0].second}});
          v.pb({abs(v2[n-1].first-v2[0].first),{v2[n-1].second,v2[0].second}});
         v.pb({abs(v2[n-1].first-v2[1].first),{v2[n-1].second,v2[1].second}});
          v.pb({abs(v2[n-2].first-v2[0].first),{v2[n-2].second,v2[0].second}});

          sort(v.begin(),v.end());
          reverse(v.begin(),v.end());
          ll x1 = v[0].second.first;
          ll y1 = v[0].second.second;
          ll x2 = v[1].second.first;
          ll y2 = v[1].second.second;
          if(x1!=x2 || y1!=y2)
          {
              cout << v[1].first << nl;
          }
          else
          {
              cout << v[2].first << nl;
          }
    }

    ///<<<<<Khel khotom>>>>>
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e2+5;

#define endl '\n'

ll num;
int cnt[5];

int main(){
	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	cout.setf(ios::fixed),cout.precision(3);
	cin>>num;
	while(num){
		int bit=num%10;
		cnt[bit%3]++;
		num/=10;
	}
	int ans;
	if(cnt[0]>0||cnt[1]>=3||cnt[2]>=3||(cnt[1]>=1&&cnt[2]>=1)){
		int tp1=cnt[1],tp2=cnt[2];
		int minn=min(cnt[1],cnt[2]);
		cnt[1]-=minn;
		cnt[2]-=minn;
		cnt[1]%=3;
		cnt[2]%=3;
		ans=0;
		if(cnt[1]) ans=cnt[1];
		if(cnt[2]) ans=cnt[2];
		cnt[1]=tp1;
		cnt[2]=tp2;
		cnt[1]%=3;
		cnt[2]%=3;
		minn=min(cnt[1],cnt[2]);
		cnt[1]-=minn;
		cnt[2]-=minn;
		if(cnt[1]==0&&cnt[2]==0) ans=0;
		else ans=min(ans,max(cnt[1],cnt[2]));
	}
	else ans=-1;
	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;

///--->>> CONTAINERS <<<---///
using i64 = int64_t;
using ll = long long;
using ld = long double;
using vi = vector<ll>;
using vvi = vector<vector< ll > >;
using vpi = vector<pair<ll,ll> >;
using pi = pair<ll,ll>;
using st = set<ll>;
using stk = stack<ll>;
using kiwi = queue<ll>;
using pkiwi = priority_queue<ll>;
using mp = map<ll,ll>;
using ump = unordered_map<ll,ll>;

///--->>> TEMPLATES <<<---///
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update >;

///--->>> MACROS<<<---///
const ll mx = 3e5+123;
#define MOD 998244353
#define mod 1000000007
#define isb(z) __builtin_popcount(z)
#define lisb(z) __builtin_popcountll(z)
#define iclz(z) __builtin_clz(z)
#define lclz(z) __builtin_clzll(z)
#define ictz(z) __builtin_ctz(z)
#define lctz(z) __builtin_ctzll(z)
#define REP(i,n) for (ll i=1;i<=n;++i)
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

///--->>>OPTIMIZE<<<---///
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")

///--->>> DEBUGGER<<<---///
#define dbg(args...) do {cerr<<#args<<" : "; diraf(args); } while(0)
void diraf ()  {        cerr << endl;}
template < typename T, typename ... hello>void diraf( T arg, const hello &... rest) {cerr<<arg<< ' ';diraf(rest...);}

///--->>> RANDOMIZER<<<---///
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
/* usage - just do rng() */

int main(int argc, char* argv[]){
    fastio;
    cin.exceptions(cin.failbit);
    ll n, tmp, cnt = 0; cin>>n;
    tmp = n;
    ll digits = floor(log10(n)) + 1;
    if(n%3==0){
        cout<<0<<endl;
        return 0;
    }
    vi dig(digits);
    pkiwi subSumDig;
    for(auto& x:dig)
        x = tmp % 10, tmp/=10;
    ll subSet = 1<<digits;

    for(ll i = 1; i<subSet; ++i){
        ll sum = 0, cnt = 0;
        for(ll j = 0; j<digits; ++j){
            if(i & (1<<j))
                sum+=dig[j], cnt++;
        }
        if(sum%3==0)
        subSumDig.emplace(cnt);
       /// dbg(i, sum);
    }

    if(subSumDig.empty()){
        cout<<-1<<endl;
        return 0;
    }
    cout<<digits - subSumDig.top()<<endl;

return 0;
}