#include <bits/stdc++.h>
#include <bits/extc++.h>

#define ll long long
#define sz(x) ((int) (x).size())
#define all(x) (x).begin(), (x).end()
#define vi vector<int>
#define pii pair<int, int>
#define rep(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;
template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;

struct binmat {
    int n;
    vector<ll> a;
    binmat(int n) : n(n), a(n) {}
    void eye() {
        rep(i, 0, n) {
            a[i] = (1ll << i);
        }
    }
    void set(int i, int j, bool b) {
        if((a[i] >> j & 1) != b) {
            a[i] ^= (1ll << j);
        }
    }
    bool get(int i, int j) const {
        return a[i] >> j & 1;
    }
    binmat transpose() const {
        binmat B(n);
        rep(i, 0, n) rep(j, 0, n) {
            B.set(j, i, get(i, j));
        }
        return B;
    }
    ll operator*(ll vec) const {
        ll ans = 0;
        rep(i, 0, n) {
            bool b = 0;
            rep(k, 0, n) {
                b ^= get(i, k) && (vec >> k & 1);
            }
            if(b) ans ^= (1ll << i);
        }
        return ans;
    }
    binmat operator*(const binmat &o) const {
        assert(n == o.n);
        binmat B(n);
        binmat oT = o.transpose();
        rep(i, 0, n) {
            rep(j, 0, n) {
                B.set(i, j, __builtin_popcountll(a[i] & oT.a[j]) % 2);
            }
        }
        return B;
    }
    bool invert() {
        binmat R(n);
        R.eye();
        rep(i, 0, n) {
            int p = -1;
            rep(j, i, n) {
                if(get(j, i)) {
                    p = j;
                    break;
                }
            }
            if(p == -1) return false;
            swap(a[i], a[p]);
            swap(R.a[i], R.a[p]);
            rep(j, i + 1, n) {
                if(get(j, i)) {
                    a[j] ^= a[i];
                    R.a[j] ^= R.a[i];
                }
            }
        }
        for(int i = n - 1; i >= 0; i--) {
            rep(j, 0, i) {
                if(get(j, i)) {
                    a[j] ^= a[i];
                    R.a[j] ^= R.a[i];
                }
            }
        }
        *this = R;
        return true;
    }
};

struct custom_hash {
    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);
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    string s;
    cin >> s;
    int offset = 1;
    while(!s.empty() && s[0] == '0') {
        s.erase(s.begin());
        offset++;
    }
    while(!s.empty() && s.back() == '0') {
        s.pop_back();
    }
    if(s.empty()) {
        cout << -1 << '\n';
        return 0;
    }
    int n = s.length() - 1;
    if(n <= 1) {
        cout << offset << ' ' << offset + 1 << '\n';
        return 0;
    }
    binmat B(n);
    rep(i, 1, n) {
        B.set(i, i - 1, 1);
    }
    rep(i, 0, n) {
        B.set(i, n - 1, s[i] == '1');
    }
    binmat Binv = B;
    Binv.invert();
    __gnu_pbds::gp_hash_table<ll, int, custom_hash> fuck;

    ll ans = LLONG_MAX;
    ll vec = 1;
    rep(i, 0, 1 << (n / 2)) {
        if(fuck.count(vec) == 0) {
            fuck[vec] = i;
        }
        if(vec == 1 && i > 0) {
            ans = min(ans, (ll)i);
        }
        vec = Binv * vec;
    }

    rep(i, 0, n / 2) {
        B = B * B;
    }
    vec = 1;
    rep(i, 0, 1 << ((n + 1) / 2)) {
        if(fuck.count(vec)) {
            ll val = 1ll * fuck[vec] + i * (1ll << (n / 2));
            if(val != 0) {
                ans = min(ans, val);
            }
        }
        vec = B * vec;
    }
    cout << offset << ' ' << offset + ans << '\n';
}


//#define fi first
//#define sc second
//#define mp(x,y) make_pair(x,y)
//#define pa pair<ll,ll>
#include<bits/stdc++.h>
#define ll long long
#define LL __int128
#define in(x) x=read()
using namespace std;
ll hi;
inline LL read()
{
    LL x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')
	{
		x=(x<<1)+(ch^48);
		if(x == 0 && ch == '0')hi++;
		ch=getchar();
	}
    return x*f;
}
ll www,M;
ll mod(ll x)
{
	if(x & (1ll<<www))x^=M;
	return x;
}
ll mul(ll x,ll y)
{
	ll ans=0;
	for(int s=0;;s++,y=mod(y<<1))
	{
		if((1ll<<s) > x)return ans;
		if((1ll<<s) & x)ans =y^ans;
	}
}
map<ll,ll>mp;
int main()
{
	in(M);
	while(M%2==0)M/=2;
	www=__lg(M);
	if(M == 0)
	{
		puts("-1");
		return 0;
	}
	printf("%lld ",hi+1);
	mp[1]=1;
	ll nw = 1;
	for(int s=2;s<262144;s++)
	{
		nw = mod(nw<<1);
		mp[nw] = s;
//		if(s == 33911 || s==33769)
//		cout<<s<<"->"<<nw<<endl;
	}
	nw=mod(nw<<1);
	ll fk=nw;
	for(int s=1;s<=262144;s++)
	{
		if(mp.count(fk) == 1)
		{
			cout<<hi+1+s*262144ll-mp[fk]-(s-1)<<endl;
//			cerr<<s<<"->"<<mp[fk]<<endl;
			return 0;
		}
		fk = mul(fk,nw);
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const long long B=500000;
long long zs1,m,zs;
string s;
map<int,int> hash;
long long mo(long long x)
{
	if(x&(1<<m)) return (x^zs);
	else return x;
}
long long mul(long long x,long long y)
{
	long long ans=0;
	for(int i=0;i<m;i++)
	{
	    if(x&(1ll<<i)) ans^=y;
		y=mo(y*2);
	}
	return ans;
}
signed main()
{
	ios::sync_with_stdio(false);
	cin>>s;
	for(int i=0;i<s.size();i++)
	{
	if(!(s[i]-'0')) zs1++;
	else
	{
		int len=s.size()-i;
		for(int j=i;j<s.size();j++) zs+=(s[j]-'0')*(1<<(j-i));
	    break;
	}
	}
	if(zs==0) {cout<<-1; return 0;}
	long long t=zs;
	while(t) t/=2,m++;
	m--;
	long long dq=1;
	for(int i=1;i<B;i++)
	{
	dq=mo(dq*2);
	if(dq==(zs^1))
	{
		return 0;
	}
	hash[dq]=i;
    }
	dq=mo(dq*2);
	long long dq1=dq;
	for(int i=1;i<B;i++)
	{
		if(hash[dq1])
		{
	        cout<<zs1+1<<" "<<i*B-hash[dq1]+zs1+1;
		    return 0;
		}
		dq1=mul(dq1,dq);
	}
	cout<<-1;
    return 0;
}


#include<bits/stdc++.h>
#define lld long long int
#define vec vector<lld>
#define pll pair<lld,lld>
#define pb push_back
#define ss second
#define ff first
#define mp make_pair
#define MOD 1000000007
#define answer cout<<endl<<"answer : ";
#define messi ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define rep(i, n) for (int i = 0; i < (n); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
using namespace std;
const int N = 200002, MOD = 998244353;
lld a[N], f[N], rf[N], pk[N];

lld pw(lld x, lld k) {
    lld res = 1;
    for (int i = 30; i >= 0; i--) {
        res = res * res % MOD;
        if (k & (1 << i))
            res = res * x % MOD;
    }
    return res;
}
lld rev(lld x) {
    return pw(x, MOD - 2);
}

int main() {
    messi //lld t=0;cin>>t;while(t--){
	lld n, k, r = 0;
    cin >> n >> k;
    if (k == 1) {
        cout << 0;
        return 0;
    }
    f[0] = rf[0] = 1;
    for (int i = 1; i <= n; i++) {
        f[i] = f[i - 1] * i % MOD;
        rf[i] = rev(f[i]);
    }
    rep(i, n)
        cin >> a[i];
    rep(i, n)
        if (a[i] != a[(i + 1) % n])
            r++;
    lld ans = 0, cc;
    for (int i = 0; 2 * i <= r; i++) {
        ans = (ans + f[r] % MOD * rf[i] % MOD * rf[i] % MOD * rf[r - 2 * i] % MOD * pw(k - 2, r - 2 * i) % MOD) % MOD;
    }
    //answer
    cout << ((pw(k, r) + MOD - ans) % MOD * rf[2] % MOD) * pw(k, n - r) % MOD<<endl;
//}
    return 0;
}
/*  CODED BY:-
           __        __
 /\   /\  |__)  /\  |  \ |__| \ /  /\
/~~\ /~~\ |  \ /~~\ |__/ |  |  |  /~~\

*/


//#pragma GCC optimize ("Ofast")
#include <bits/stdc++.h>
//#define int long long
#define endl '\n'
typedef long long ll;
const ll mod=998244353ll;
using namespace std;
ll dp[2011][4011];
ll h[300001];
int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll n,k;cin>>n>>k;
    for (int i=1;i<=n;i++) cin>>h[i];
    h[n+1]=h[1];
    vector<int>v={h[1]};
    ll p=1ll;
    for (int i=2;i<=n+1;i++){
        if (h[i]!=h[i-1]) v.push_back(h[i]);
        else p=(p*k)%mod;
    }
    int cnt=0;
    for (auto i:v) h[++cnt]=i;
    n=cnt-1;
    if (h[1]==h[2]){
        dp[2][2000]=k;
    } else {
        dp[2][2001]=1ll;
        dp[2][1999]=1ll;
        dp[2][2000]=k-2ll;
    }
    for (int i=2;i<=n;i++){
        for (int j=2000-i;j<=2000+i;j++){
            dp[i+1][j]=(dp[i+1][j]+dp[i][j]*(k-2ll))%mod;
            dp[i+1][j+1]=(dp[i+1][j+1]+dp[i][j])%mod;
            dp[i+1][j-1]=(dp[i+1][j-1]+dp[i][j])%mod;
        }
    }
    ll sum=0ll;
    for (int i=2001;i<=2000+n;i++) sum=(sum+dp[n+1][i])%mod;
    cout<<(sum*p)%mod;
    return 0;
}
/*
//#pragma GCC optimize ("Ofast")
#include <bits/stdc++.h>
//#define int long long
#define endl '\n'
typedef long long ll;
using namespace std;
int a[300001];
map<int,int>mp;
int val[300001];
set<int>g[300001];
int ans[300001];
void solve(){
    vector<pair<pair<int,int>,int> >q;
    int n;cin>>n;
    set<int>nn;
    for (int i=1;i<=n;i++) cin>>a[i],nn.insert(a[i]);
    int cnt=0;
    for (auto i:nn) mp[i]=++cnt,val[cnt]=i;
    vector<int>v;
    for (int i=1;i<=n;i++){
        g[mp[a[i]].insert(i);
        v.push_back(mp[a[i]]);
    }
    sort(v.begin(),v.end());
    int m;cin>>m;
    for (int i=1;i<=m;i++){
        int k,pos;cin>>k>>pos;
        q.push_back({{k,pos},i});
    }
    sort(q.begin(),q.end());
    set<int>sub_seq;
    int K=0;
    for (int i=0;i<m;i++){
        int k=q[i].first.first;
        int pos=q[i].first.second;
        int ind=q[i].second;
        while (K<k){
            K++;
            int cur=v[n-K];
            if (sub_seq.empty()){
                sub_seq.insert(*g[cur].rbegin());
            } else {
                int j=-1;
                auto it=g[cur].lower_bound(*sub_seq.begin());
                if (it!=g[cur].begin()) it--;
                sub_seq.insert(*it);
                g[cur].erase(it);
            }
        }
        ans[ind]=sub_se
    }
}
int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int tt;cin>>tt;
    while (tt--){
        solve();
    }
    return 0;
}
*/


#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using pii=pair<int, int>;
inline int read(){
	register int res=0, c;
	while(c=getchar(), c<'0'||c>'9');
	do{
		res=(res*10)+(c^48);
	} while(c=getchar(), c>='0'&&c<='9');
	return res;
}
const int mod = 998244353;
int qpow(int n, int k){
	int res = 1;
	while(k){
		if(k&1)res = 1ll*res*n%mod;
		n = 1ll*n*n%mod;
		k>>=1;
	}
	return res;
}
int main(int argc, char* argv[]){
	int N=read(), K=read();
	vector<int> s(N);
	for(int i=0; i<N; i++){
		s[i]=read();
	}
	int cnt = 0;
	for(int i=0; i<N; i++){
		if(s[i]==s[(i+1)%N])cnt++;
	}
	vector<vector<int>> C(2001, vector<int>(2001));
	C[0][0]=1;
	for(int i=1; i<=2000; i++){
		C[i][0]=C[i][i]=1;
		for(int j=1; j<i; j++){
			C[i][j] = (C[i-1][j-1] + C[i-1][j])%mod;
		}
	}
	int rev2 = qpow(2, mod-2);
	int ans = 0;
	for(int j=0; j<N-cnt; j++){
		int now = qpow(K-2, j);
		now = 1ll*now*C[N-cnt][j]%mod;
		if((N-cnt-j)&1){
			now = 1ll*now*qpow(2, N-cnt-j-1)%mod;
		}else{
			now = 1ll*now*(qpow(2, N-cnt-j) - C[N-cnt-j][(N-cnt-j)>>1] + mod)%mod;
			now = 1ll*now*rev2%mod;
		}
		ans = (ans + now) % mod;
	}
	ans = 1ll* ans * qpow(K, cnt) % mod;
	printf("%d\n", ans);
	return 0;
}


//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <cmath>
#include <unordered_set>
#include <unordered_map>
#include <iomanip>
#include <deque>
#include <chrono>
#include <cassert>
#include <bitset>
#include <random>

using namespace std;

typedef long long li;
typedef  long double ld;
const li MAX = 1e5 + 5;

li inf = (li)30000;
li mod = (li)998244353;
li n, k, a[MAX], f[MAX], rev[MAX], power[MAX], any[MAX];

li bin(li num, li power) {
    if (power == 0) return 1;
    else {
        li ret;
        if (power & 1) ret = (num * bin(num, power - 1)) % mod;
        else {
            ret = bin(num, power / 2);
            ret = (ret * ret) % mod;
        }
        return ret;
    }
}

li c(li n, li k) {
    return (((f[n] * rev[n - k]) % mod) * rev[k]) % mod;
}

void solve() {
    cin >> n >> k;
    f[0] = 1;
    any[0] = 1;
    rev[0] = 1;
    power[0] = 1;
    for (int i = 1; i < MAX; i++) {
        f[i] = (f[i - 1] * i) % mod;
        any[i] = (any[i - 1] * (k - 2)) % mod;
        rev[i] = (bin(i, mod - 2) * rev[i - 1]) % mod;
        power[i] = (power[i - 1] * 2) % mod;
    }

    li m = 0, ans = 0;
    for (int i = 0; i < n; i++) cin >> a[i];
    for (int i = 0; i < n; i++) {
        if (a[i] != a[(i + 1) % n]) m++;
    }

    for (int i = 1; i <= m; i++) {
        li ad;
        if (i % 2 == 1) ad = (((c(m, i) * power[i]) % mod) * rev[2]) % mod;
        else {
            li act = (power[i] + mod - c(i, i / 2)) % mod;
            ad = (((c(m, i) * act) % mod) * rev[2]) % mod;
        }
        ad *= any[m - i];
        ans += ad;
        ans %= mod;
    }

    for (int i = 0; i < n - m; i++) ans = (ans * k) % mod;
    cout << ans;
}

int main() {
    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
    ios::sync_with_stdio(0);
    li q;
    q = 1;
    while (q--) solve();

    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);cerr.tie(0)
#define mp make_pair
#define xx first
#define yy second
#define dif(x) ((x).yy-(x).xx)
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(x) (x).begin(),(x).end()
#define exist(a,x) find(all(a),x)!=a.end()
#define ub(a,x) upper_bound(all(a),x)
#define lb(a,x) lower_bound(all(a),x)
#define inv(n) power((n), mod - 2)
#define ff(i,a,b) for (int (i) = (a); (i) < (b); (i)++)
#define fff(i,a,b) for (int (i) = (a); (i) <= b; (i)++)
#define bff(i,a,b) for (int (i) = (b)-1; (i) >= (a); (i)--)
#define bfff(i,a,b) for (int (i) = (b); (i) >= (a); (i)--)

using namespace std;
long double typedef ld;
unsigned int typedef ui;
long long int typedef li;
pair<int,int> typedef pii;
pair<li,li> typedef pli;
vector<vector<int>> typedef graph;
unsigned long long int typedef ull;
const ld PI = 3.14159265359;
//const int mod = 998244353;
const int mod = 1000000007;
const li inf = 9223372036854775807ll;

using namespace __gnu_pbds;
template <class T> using oset = tree<T, null_type,greater<T>, rb_tree_tag,tree_order_statistics_node_update>;
template <class T> using omset = tree<T, null_type,less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

inline int power(li _a, int _n)
{
        li _c = 1;
        while (_n>0)
        {
                if (_n % 2) _c = _c * _a%mod;
                _a = _a * _a%mod;
                _n/=2;
        }
        return _c;
}

inline int geom(li _a, int _n) //suma 1 + a + a^2 + ... + a^(n-1)
{
    if (_a == 0) return 0;
        if (_a == 1) return _n;
        return ((li)power(_a, _n) - 1) * inv(_a - 1) % mod;
}

pli _r;

li bigmod(li _a, li _b, li _m) //ogromni mod
{
    if (_a==0) return 0;
    if (_a%2==1) return (_b + 2*bigmod(_a/2,_b,_m))%_m;
    return 2*bigmod(_a/2,_b,_m)%_m;
}

void euklid(li _a, li _b)
{
    if (_b==1)
    {
        _r = mp(1,-_a+1);
        return;
    }

    euklid(_b,_a%_b); //cout<<r.xx<<" "<<r.yy<<endl;
    _r=mp(_r.yy,_r.xx-_r.yy*(_a/_b));
}

li kinez(li _x, li _a, li _y, li _b)
{
    if (_x==_y) return _x;
    if (_a>_b) {swap(_a,_b); swap(_x,_y);}

    euklid(_b,_a); (_r.xx*=(_x-_y))%=(_a*_b);
    return (bigmod(_b,_r.xx,_a*_b)+_y)%(_a*_b);
}

inline li sum(int _n) {return ((li)_n*(_n+1))/2;}

inline li kv(int _n) {return ((li)_n*(_n+1)*(2*_n+1))/6;}

//Note to self: Check for overflow

int kvsum(li x)
{
    li res=x*(x+1)%mod;
    res=res*(2*x+1)%mod;
    return res*inv(6)%mod;
}

int zbirost(li x, li y)
{
    x++; y++;
    if (x%3==0 || y%3==0) return x*y/3*3;
    if (x%3==1 && y%3==1) return x*y/3*3 + (x+y-2)%3;
    if (x%3==2 && y%3==2) return x*y/3*3 - 3 + (x+y-2)%3 + (x+y-3)%3 + (x+y-3)%3 + (x+y-4)%3;
    else return x*y/3*3 + (x+y-2)%3 + (x+y-3)%3;
}

int summ(int x)
{
    return (x/3)*(x - 1 + x%3)/2;
}

int presum(li x)
{
    //summ(0) + summ(1) + summ(2) + ... + summ(x), gde je summ(x) zbir prefiksa u nizu 0 0 0 1 1 1 2 2 2 3 3 3 ... koji je indeksiran od 0

    //summ(x)=3*(x/3)*(x/3 + 1)/2 - (x/3)*(2-x%3)

    x++; //neko shiftovanje nmp glup sam

    /*int res=0;
    fff(i,0,x) res+=summ(i);
    return res;*/

    li res=x*3%mod*(sum(x/3)%mod);
    res-=kvsum(x/3)*9%mod;
    res%=mod; if (res<0) res+=mod;
    res-=summ(x);

    if (x%3==0) res+=x/3;

    return res;
}

li presumsum(li x)
{
    return x*(x+1)%mod*(x+2)%mod*inv(6)%mod;
}

li oduzm_red(int p, int k)
{
    //(sum(p) + sum(p+1) + sum(p+2) + sum(p+3)) + (sum(p+2)+sum(p+3)+sum(p+4)+sum(p+5)) + ...
    //suma prvih k+1 elem.  blokovi su mod 4

    int kk=(k/4*4+3)/2+2;
    li res=presumsum(p+kk)+presumsum(p+kk-2)-presumsum(p+1)-presumsum(p-1);
    if (k%4<=2) (res-=sum(p+kk))%=mod;
    if (k%4<=1) (res-=sum(p+kk-1))%=mod;
    if (k%4<=0) (res-=sum(p+kk-2))%=mod;
    if (res<0) res+=mod;

    //cout<<p<<" "<<k<<" "<<kk<<": "<<res<<endl;
    return res;
}

int dunkcija(int x, int y)
{
    if (2*x>y) return 0;

    li res=0;
    if (y%2==0)
    {
        int fakex=y/2; //cout<<fakex<<" "<<x<<": ";
        res+=(fakex-x+1)*(sum(fakex)%mod)+(fakex-x)*(sum(fakex+1)%mod);
        res-=oduzm_red(x-1,y-2*x); if (res<0) res+=mod;

        return res;
    }
    else
    {
        res=dunkcija(x,y-1);
        li fakex=y/2+1;

        res+=(fakex-x)*fakex+fakex/2;
        if (y%4==1) res-=x/2;
        else res-=(x+1)/2;
        return res%mod;
    }
}

int pref(int n, int m)
{
    int res=(presum(n+m)-presum(n-1)-presum(m-1))%mod;
    (res+=zbirost(n,m))%=mod;

    //cout<<dunkcija(0,n)<<" "<<dunkcija(0,m)<<endl;

    if (2*n>=m) (res+=dunkcija(0,m))%=mod;
    else (res+=dunkcija(0,m)-dunkcija(n+1,m))%=mod;

    if (2*m>=n) (res+=dunkcija(0,n))%=mod;
    else (res+=dunkcija(0,n)-dunkcija(m+1,n))%=mod;

    return (res<0)?res+mod:res;

    /*int res=0;
    fff(i,0,m) res+=summ(n+i)-summ(i-1);
    return res;*/
}

int kurac(int x)
{
    return x-(x/4)*2;
}

int podeli(li x, li y, li n, li m)
{
    int res=(pref(n,m)+pref(x-1,y-1)-pref(n,y-1)-pref(x-1,m))%mod;

    return (res<0)?res+mod:res;

    /*li res=0;
    fff(i,x,n) fff(j,y,m)
    {
        if (i==2 && j==2) res+=4;
        else if (j>2*i) res+=i+kurac(j-2*i);
        else if (i>2*j) res+=j+kurac(i-2*j);
        else res+=(i+j)/3+(i+j)%3;
    }
    return res%mod;*/
}

int main()
{
    FAST;

    int t,x,y,n,m;
    cin>>t; while(t--)
    {
        cin>>x>>y>>n>>m;
        x--; y--; n--; m--;
        int res=podeli(x,y,n,m);
        fff(i,x,n) fff(j,y,m)
        {
            if (j>=2*i)
            {
                res-=(i+j)/3+(i+j)%3;
                //res+=i+kurac(j-2*i);
            }
            else if (i>=2*j)
            {
                res-=(i+j)/3+(i+j)%3;
                //res+=j+kurac(i-2*j);
            }
        }
        if (x==2 && y==2) res+=2;
        cout<<res<<endl;
    }

    /*while (true)
    {
        int x,y; cin>>x>>y;
        cout<<pref(x,y)<<endl;
    }*/
}

//Note to self: Check for overflow


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);cerr.tie(0)
#define mp make_pair
#define xx first
#define yy second
#define dif(x) ((x).yy-(x).xx)
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(x) (x).begin(),(x).end()
#define exist(a,x) find(all(a),x)!=a.end()
#define ub(a,x) upper_bound(all(a),x)
#define lb(a,x) lower_bound(all(a),x)
#define inv(n) power((n), mod - 2)
#define ff(i,a,b) for (int (i) = (a); (i) < (b); (i)++)
#define fff(i,a,b) for (int (i) = (a); (i) <= b; (i)++)
#define bff(i,a,b) for (int (i) = (b)-1; (i) >= (a); (i)--)
#define bfff(i,a,b) for (int (i) = (b); (i) >= (a); (i)--)

using namespace std;
long double typedef ld;
unsigned int typedef ui;
long long int typedef li;
pair<int,int> typedef pii;
pair<li,li> typedef pli;
vector<vector<int>> typedef graph;
unsigned long long int typedef ull;
const ld PI = 3.14159265359;
//const int mod = 998244353;
const int mod = 1000000007;
const li inf = 9223372036854775807ll;

using namespace __gnu_pbds;
template <class T> using oset = tree<T, null_type,greater<T>, rb_tree_tag,tree_order_statistics_node_update>;
template <class T> using omset = tree<T, null_type,less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

inline int power(li _a, int _n)
{
        li _c = 1;
        while (_n>0)
        {
                if (_n % 2) _c = _c * _a%mod;
                _a = _a * _a%mod;
                _n/=2;
        }
        return _c;
}

inline int geom(li _a, int _n) //suma 1 + a + a^2 + ... + a^(n-1)
{
    if (_a == 0) return 0;
        if (_a == 1) return _n;
        return ((li)power(_a, _n) - 1) * inv(_a - 1) % mod;
}

pli _r;

li bigmod(li _a, li _b, li _m) //ogromni mod
{
    if (_a==0) return 0;
    if (_a%2==1) return (_b + 2*bigmod(_a/2,_b,_m))%_m;
    return 2*bigmod(_a/2,_b,_m)%_m;
}

void euklid(li _a, li _b)
{
    if (_b==1)
    {
        _r = mp(1,-_a+1);
        return;
    }

    euklid(_b,_a%_b); //cout<<r.xx<<" "<<r.yy<<endl;
    _r=mp(_r.yy,_r.xx-_r.yy*(_a/_b));
}

li kinez(li _x, li _a, li _y, li _b)
{
    if (_x==_y) return _x;
    if (_a>_b) {swap(_a,_b); swap(_x,_y);}

    euklid(_b,_a); (_r.xx*=(_x-_y))%=(_a*_b);
    return (bigmod(_b,_r.xx,_a*_b)+_y)%(_a*_b);
}

inline li sum(int _n) {return ((li)_n*(_n+1))/2;}

inline li kv(int _n) {return ((li)_n*(_n+1)*(2*_n+1))/6;}

//Note to self: Check for overflow

int kvsum(li x)
{
    li res=x*(x+1)%mod;
    res=res*(2*x+1)%mod;
    return res*inv(6)%mod;
}

int zbirost(li x, li y)
{
    x++; y++;
    if (x%3==0 || y%3==0) return x*y/3*3;
    if (x%3==1 && y%3==1) return x*y/3*3 + (x+y-2)%3;
    if (x%3==2 && y%3==2) return x*y/3*3 - 3 + (x+y-2)%3 + (x+y-3)%3 + (x+y-3)%3 + (x+y-4)%3;
    else return x*y/3*3 + (x+y-2)%3 + (x+y-3)%3;
}

int summ(int x)
{
    return (x/3)*(x - 1 + x%3)/2;
}

int presum(li x)
{
    //summ(0) + summ(1) + summ(2) + ... + summ(x), gde je summ(x) zbir prefiksa u nizu 0 0 0 1 1 1 2 2 2 3 3 3 ... koji je indeksiran od 0

    //summ(x)=3*(x/3)*(x/3 + 1)/2 - (x/3)*(2-x%3)

    x++; //neko shiftovanje nmp glup sam

    /*int res=0;
    fff(i,0,x) res+=summ(i);
    return res;*/

    li res=x*3%mod*(sum(x/3)%mod);
    res-=kvsum(x/3)*9%mod;
    res%=mod; if (res<0) res+=mod;
    res-=summ(x);

    if (x%3==0) res+=x/3;

    return res;
}

int pref(int n, int m)
{
    int res=(presum(n+m)-presum(n-1)-presum(m-1))%mod;
    (res+=zbirost(n,m))%=mod;
    return (res<0)?res+mod:res;

    /*int res=0;
    fff(i,0,m) res+=summ(n+i)-summ(i-1);
    return res;*/
}

int kurac(int x)
{
    return x-(x/4)*2;
}

int podeli(li x, li y, li n, li m)
{
    int res=(pref(n,m)+pref(x-1,y-1)-pref(n,y-1)-pref(x-1,m))%mod;
    return (res<0)?res+mod:res;

    /*li res=0;
    fff(i,x,n) fff(j,y,m)
    {
        if (i==2 && j==2) res+=4;
        else if (j>2*i) res+=i+kurac(j-2*i);
        else if (i>2*j) res+=j+kurac(i-2*j);
        else res+=(i+j)/3+(i+j)%3;
    }
    return res%mod;*/
}

int main()
{
    FAST;

    int t,x,y,n,m;
    cin>>t; while(t--)
    {
        cin>>x>>y>>n>>m;
        x--; y--; n--; m--;
        int res=podeli(x,y,n,m);
        fff(i,x,n) fff(j,y,m)
        {
            if (j>=2*i) res+=i+kurac(j-2*i)-(i+j)/3-(i+j)%3;
            else if (i>=2*j) res+=j+kurac(i-2*j)-(i+j)/3-(i+j)%3;
        }
        if (x==2 && y==2) res+=2;
        cout<<res<<endl;
    }

    /*while (true)
    {
        int x,y; cin>>x>>y;
        cout<<pref(x,y)<<endl;
    }*/
}

//Note to self: Check for overflow


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);cerr.tie(0)
#define mp make_pair
#define xx first
#define yy second
#define dif(x) ((x).yy-(x).xx)
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(x) (x).begin(),(x).end()
#define exist(a,x) find(all(a),x)!=a.end()
#define ub(a,x) upper_bound(all(a),x)
#define lb(a,x) lower_bound(all(a),x)
#define inv(n) power((n), mod - 2)
#define ff(i,a,b) for (int (i) = (a); (i) < (b); (i)++)
#define fff(i,a,b) for (int (i) = (a); (i) <= b; (i)++)
#define bff(i,a,b) for (int (i) = (b)-1; (i) >= (a); (i)--)
#define bfff(i,a,b) for (int (i) = (b); (i) >= (a); (i)--)

using namespace std;
long double typedef ld;
unsigned int typedef ui;
long long int typedef li;
pair<int,int> typedef pii;
pair<li,li> typedef pli;
vector<vector<int>> typedef graph;
unsigned long long int typedef ull;
const ld PI = 3.14159265359;
//const int mod = 998244353;
const int mod = 1000000007;
const li inf = 9223372036854775807ll;

using namespace __gnu_pbds;
template <class T> using oset = tree<T, null_type,greater<T>, rb_tree_tag,tree_order_statistics_node_update>;
template <class T> using omset = tree<T, null_type,less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

inline int power(li _a, int _n)
{
        li _c = 1;
        while (_n>0)
        {
                if (_n % 2) _c = _c * _a%mod;
                _a = _a * _a%mod;
                _n/=2;
        }
        return _c;
}

inline int geom(li _a, int _n) //suma 1 + a + a^2 + ... + a^(n-1)
{
    if (_a == 0) return 0;
        if (_a == 1) return _n;
        return ((li)power(_a, _n) - 1) * inv(_a - 1) % mod;
}

pli _r;

li bigmod(li _a, li _b, li _m) //ogromni mod
{
    if (_a==0) return 0;
    if (_a%2==1) return (_b + 2*bigmod(_a/2,_b,_m))%_m;
    return 2*bigmod(_a/2,_b,_m)%_m;
}

void euklid(li _a, li _b)
{
    if (_b==1)
    {
        _r = mp(1,-_a+1);
        return;
    }

    euklid(_b,_a%_b); //cout<<r.xx<<" "<<r.yy<<endl;
    _r=mp(_r.yy,_r.xx-_r.yy*(_a/_b));
}

li kinez(li _x, li _a, li _y, li _b)
{
    if (_x==_y) return _x;
    if (_a>_b) {swap(_a,_b); swap(_x,_y);}

    euklid(_b,_a); (_r.xx*=(_x-_y))%=(_a*_b);
    return (bigmod(_b,_r.xx,_a*_b)+_y)%(_a*_b);
}

inline li sum(int _n) {return ((li)_n*(_n+1))/2;}

inline li kv(int _n) {return ((li)_n*(_n+1)*(2*_n+1))/6;}

//Note to self: Check for overflow

int kvsum(li x)
{
    li res=x*(x+1)%mod;
    res=res*(2*x+1)%mod;
    return res*inv(6)%mod;
}

int zbirost(li x, li y, li n, li m)
{
    li ostatak=(n-x+1)*(m-y+1)%3;
    li res=0;

    if (ostatak==1) res+=(x+y)%3;
    else if (ostatak==2) res+=(x+y)%3+(x+y-1)%3;

    res+=(n-x+1)*(m-y+1)/3*3;

    return res%mod;
}

int summ(int x)
{
    return (x/3)*(x - 1 + x%3)/2;
}

int presum(li x)
{
    //summ(0) + summ(1) + summ(2) + ... + summ(x), gde je summ(x) zbir prefiksa u nizu 0 0 0 1 1 1 2 2 2 3 3 3 ... koji je indeksiran od 0

    //summ(x)=3*(x/3)*(x/3 + 1)/2 - (x/3)*(2-x%3)

    x++; //neko shiftovanje nmp glup sam

    /*int res=0;
    fff(i,0,x) res+=summ(i);
    return res;*/

    li res=x*3%mod*(sum(x/3)%mod);
    res-=kvsum(x/3)*9%mod;
    res%=mod; if (res<0) res+=mod;
    res-=summ(x);

    if (x%3==0) res+=x/3;

    return res;
}

int pref(int n, int m)
{
    int res=(presum(n+m)-presum(n-1)-presum(m))%mod;
    return (res<0)?res+mod:res;

    /*int res=0;
    fff(i,0,m) res+=summ(n+i)-summ(i-1);
    return res;*/
}

int kurac(int x)
{
    return x-(x/4)*2;
}

int podeli(li x, li y, li n, li m)
{
    //int res=(pref(n,m)+pref(x-1,y-1)-pref(n,y-1)-pref(x-1,m))%mod;
    //return (res<0)?res+mod:res;

    li res=0;
    fff(i,x,n) fff(j,y,m)
    {
        if (i==2 && j==2) res+=4;
        else if (j>2*i) res+=i+kurac(j-2*i);
        else if (i>2*j) res+=j+kurac(i-2*j);
        else res+=(i+j)/3+(i+j)%3;
    }
    return res%mod;
}

int main()
{
    FAST;

    int t,x,y,n,m;
    cin>>t; while(t--)
    {
        cin>>x>>y>>n>>m;
        x--; y--; n--; m--;
        int res=podeli(x,y,n,m);
        cout<<res<<endl;
    }

    //ff(i,0,15) cout<<summ(i)<<" "; cout<<endl;
    //ff(i,0,9) cout<<presum(i)<<" "; cout<<endl;

    /*while (true)
    {
        int x; cin>>x;
        cout<<","<<presum(x)<<endl;
    }*/

    /*while (true)
    {
        int i,j; cin>>i>>j;
        int res=0;
        if (i==2 && j==2) res+=4;
        else if (j>2*i)
        {
            cout<<" "<<i<<" "<<j<<": "<<kurac(j-i)<<" - ";
            res+=i+kurac(j-i);
        }
        else if (i>2*j) res+=j+kurac(i-j);
        else res+=(i+j)/3+(i+j)%3;
        cout<<res<<endl;
    }*/
}

//Note to self: Check for overflow


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);cerr.tie(0)
#define mp make_pair
#define xx first
#define yy second
#define dif(x) ((x).yy-(x).xx)
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define all(x) (x).begin(),(x).end()
#define exist(a,x) find(all(a),x)!=a.end()
#define ub(a,x) upper_bound(all(a),x)
#define lb(a,x) lower_bound(all(a),x)
#define inv(n) power((n), mod - 2)
#define ff(i,a,b) for (int (i) = (a); (i) < (b); (i)++)
#define fff(i,a,b) for (int (i) = (a); (i) <= b; (i)++)
#define bff(i,a,b) for (int (i) = (b)-1; (i) >= (a); (i)--)
#define bfff(i,a,b) for (int (i) = (b); (i) >= (a); (i)--)

using namespace std;
long double typedef ld;
unsigned int typedef ui;
long long int typedef li;
pair<int,int> typedef pii;
pair<li,li> typedef pli;
vector<vector<int>> typedef graph;
unsigned long long int typedef ull;
const ld PI = 3.14159265359;
//const int mod = 998244353;
const int mod = 1000000007;
const li inf = 9223372036854775807ll;

using namespace __gnu_pbds;
template <class T> using oset = tree<T, null_type,greater<T>, rb_tree_tag,tree_order_statistics_node_update>;
template <class T> using omset = tree<T, null_type,less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

inline int power(li _a, int _n)
{
        li _c = 1;
        while (_n>0)
        {
                if (_n % 2) _c = _c * _a%mod;
                _a = _a * _a%mod;
                _n/=2;
        }
        return _c;
}

inline int geom(li _a, int _n) //suma 1 + a + a^2 + ... + a^(n-1)
{
    if (_a == 0) return 0;
        if (_a == 1) return _n;
        return ((li)power(_a, _n) - 1) * inv(_a - 1) % mod;
}

pli _r;

li bigmod(li _a, li _b, li _m) //ogromni mod
{
    if (_a==0) return 0;
    if (_a%2==1) return (_b + 2*bigmod(_a/2,_b,_m))%_m;
    return 2*bigmod(_a/2,_b,_m)%_m;
}

void euklid(li _a, li _b)
{
    if (_b==1)
    {
        _r = mp(1,-_a+1);
        return;
    }

    euklid(_b,_a%_b); //cout<<r.xx<<" "<<r.yy<<endl;
    _r=mp(_r.yy,_r.xx-_r.yy*(_a/_b));
}

li kinez(li _x, li _a, li _y, li _b)
{
    if (_x==_y) return _x;
    if (_a>_b) {swap(_a,_b); swap(_x,_y);}

    euklid(_b,_a); (_r.xx*=(_x-_y))%=(_a*_b);
    return (bigmod(_b,_r.xx,_a*_b)+_y)%(_a*_b);
}

inline li sum(int _n) {return ((li)_n*(_n+1))/2;}

inline li kv(int _n) {return ((li)_n*(_n+1)*(2*_n+1))/6;}

//Note to self: Check for overflow

int kvsum(li x)
{
    li res=x*(x+1)%mod;
    res=res*(2*x+1)%mod;
    return res*inv(6)%mod;
}

int zbirost(li x, li y)
{
    x++; y++;
    if (x%3==0 || y%3==0) return x*y/3*3;
    if (x%3==1 && y%3==1) return x*y/3*3 + (x+y-2)%3;
    if (x%3==2 && y%3==2) return x*y/3*3 - 3 + (x+y-2)%3 + (x+y-3)%3 + (x+y-3)%3 + (x+y-4)%3;
    else return x*y/3*3 + (x+y-2)%3 + (x+y-3)%3;
}

int summ(int x)
{
    return (x/3)*(x - 1 + x%3)/2;
}

int presum(li x)
{
    //summ(0) + summ(1) + summ(2) + ... + summ(x), gde je summ(x) zbir prefiksa u nizu 0 0 0 1 1 1 2 2 2 3 3 3 ... koji je indeksiran od 0

    //summ(x)=3*(x/3)*(x/3 + 1)/2 - (x/3)*(2-x%3)

    x++; //neko shiftovanje nmp glup sam

    /*int res=0;
    fff(i,0,x) res+=summ(i);
    return res;*/

    li res=x*3%mod*(sum(x/3)%mod);
    res-=kvsum(x/3)*9%mod;
    res%=mod; if (res<0) res+=mod;
    res-=summ(x);

    if (x%3==0) res+=x/3;

    return res;
}

li presumsum(li x)
{
    return x*(x+1)%mod*(x+2)%mod*inv(6)%mod;
}

li oduzm_red(int p, int k)
{
    //(sum(p) + sum(p+1) + sum(p+2) + sum(p+3)) + (sum(p+2)+sum(p+3)+sum(p+4)+sum(p+5)) + ...
    //suma prvih k+1 elem.  blokovi su mod 4

    int kk=(k/4*4+3)/2+2;
    li res=presumsum(p+kk)+presumsum(p+kk-2)-presumsum(p+1)-presumsum(p-1);
    if (k%4<=2) (res-=sum(p+kk))%=mod;
    if (k%4<=1) (res-=sum(p+kk-1))%=mod;
    if (k%4<=0) (res-=sum(p+kk-2))%=mod;
    if (res<0) res+=mod;

    //cout<<p<<" "<<k<<" "<<kk<<": "<<res<<endl;
    return res;
}

int dunkcija(int x, int y)
{
    if (2*x>y) return 0;

    li res=0;
    if (y%2==0)
    {
        int fakex=y/2; //cout<<fakex<<" "<<x<<": ";
        res+=(fakex-x+1)*(sum(fakex)%mod)+(fakex-x)*(sum(fakex+1)%mod);
        res-=oduzm_red(x-1,y-2*x); if (res<0) res+=mod;

        return res;
    }
    else
    {
        res=dunkcija(x,y-1);
        li fakex=y/2+1;

        res+=(fakex-x)*fakex+fakex/2;
        if (y%4==1) res-=x/2;
        else res-=(x+1)/2;
        return res%mod;
    }
}

int predukcija(int x)
{
    //racuna prefiksnu sumu za prvih x+1 elemenata eledeceg niza: 0,1,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,7,...

    int res = sum(x);
    res-=6*sum(x/3);

    //cout<<sum(x)<<"-"<<6*sum(x/3)<<" = ";

    if (x%3<=1) res+=2*(x/3);
    if (x%3<=0) res+=2*(x/3);

    res%=mod; if (res<0) res+=mod;

    //cout<<x<<": "<<res<<endl;

    return res;
}

int redunkcija(li k)
{
    //WRONG
    //ODMAH ISPRAVI
    //WRONG
    //PODHITNO IZMENI
    //??ISPARVITI
}

int paradunkcija(int x)
{
    //neka je p predukcija skraceno
    //racuna p(1)+p(3)+p(5)+...+p(x), x je garantovano neparno

    //suma po modovima hahahahhaha
    //tacnije, p(1) + p(7) + p(13) + ... itd za ostale kurceve

    li mod5 = redunkcija((x+1)/6);
    li mod1 = redunkcija((x-1)/6)+4ll*((x-1)/6);
    li mod3 = redunkcija((x-3)/6)+8ll*((x-3)/6);

    mod1+=(x-1)/6+1;
    mod3+=4*((x-1)/6+1);

    cout<<"baza: "<<redunkcija((x-1)/6)<<endl;
    cout<<"dodatak na bazu: 2 puta " << 2ll*((x-1)/6)<<endl;
    cout<<"dodatni kurac: "<<(x-1)/6+1<<endl;
    cout<<"ukupno: "<<mod1<<endl<<endl;

    return ((mod1%mod + mod5%mod)%mod + mod3%mod)%mod;

    return 0;

    /*int res=0;
    for (int i=1;i<=x;i+=2) (res+=predukcija(i))%=mod;

    return res;*/
}

int anti_dunkcija(int x, int y)
{
    if (2*x>y) return 0;

    li fx=y/2,res=-69420;
    if (y%2==1)
    {
        x--;
        res=(fx-x)*(fx-x+1)%mod*(fx+1)%mod - 2*kvsum(fx-x);
        if (res<0) res+=mod; if (res<0) res+=mod;

        res+=paradunkcija(y-2*(x+1));
    }
    else
    {
        res=anti_dunkcija(x,y-1);
        res+=predukcija(y+y/2)-predukcija(y+x-1);
    }

    return res;
}

int pref(int n, int m)
{
    int res=(presum(n+m)-presum(n-1)-presum(m-1))%mod;
    (res+=zbirost(n,m))%=mod; if (res<0) res+=mod;

    //cout<<dunkcija(0,n)<<" "<<dunkcija(0,m)<<endl;

    if (2*n>=m) (res+=dunkcija(0,m))%=mod;
    else (res+=dunkcija(0,m)-dunkcija(n+1,m))%=mod;

    if (2*m>=n) (res+=dunkcija(0,n))%=mod;
    else (res+=dunkcija(0,n)-dunkcija(m+1,n))%=mod;

    //minus visak dole

    /*if (2*n>=m) (res-=anti_dunkcija(0,m))%=mod;
    else (res-=anti_dunkcija(0,m)-anti_dunkcija(n+1,m))%=mod;

    if (2*m>=n) (res-=anti_dunkcija(0,n))%=mod;
    else (res-=anti_dunkcija(0,n)-anti_dunkcija(m+1,n))%=mod;*/

    return (res<0)?res+mod:res;

    /*int res=0;
    fff(i,0,m) res+=summ(n+i)-summ(i-1);
    return res;*/
}

int kurac(int x)
{
    return x-(x/4)*2;
}

int podeli(li x, li y, li n, li m)
{
    int res=(pref(n,m)+pref(x-1,y-1)-pref(n,y-1)-pref(x-1,m))%mod;

    return (res<0)?res+mod:res;

    /*fff(i,x,n) fff(j,y,m)
    {
        if (i==2 && j==2) res+=4;
        else if (j>2*i)
        {
            res+=i+kurac(j-2*i);
            res-=(i+j)/3+(i+j)%3;
        }
        else if (i>2*j)
        {
            res+=j+kurac(i-2*j);
            res-=(i+j)/3+(i+j)%3;
        }
    }
    return res%mod;*/
}

int main()
{
    FAST;

    int t,x,y,n,m;
    cin>>t; while(t--)
    {
        cin>>x>>y>>n>>m;
        x--; y--; n--; m--;
        int res=podeli(x,y,n,m);
        fff(i,x,n) fff(j,y,m)
        {
            if (j>=2*i)
            {
                res-=(i+j)/3+(i+j)%3;
                //res+=i+kurac(j-2*i);
            }
            else if (i>=2*j)
            {
                res-=(i+j)/3+(i+j)%3;
                //res+=j+kurac(i-2*j);
            }
        }
        if (x==2 && y==2) res+=2;
        cout<<res<<endl;
    }

    /*while (true)
    {
        int x,y; cin>>x>>y;
        cout<<anti_dunkcija(x,y)<<endl;
    }*/

    /*while (true)
    {
        int x; cin>>x;
        cout<<paradunkcija(x)<<endl;
    }*/
}

//Note to self: Check for overflow


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mem0(x) memset(x,0,sizeof x)
int main(){
	int a,nowp,stk[1010];
	nowp=0;
	while(~scanf("%d",&a)){
		stk[++nowp]=a;
	}
	for(int i=nowp;i>=1;i--){
		int t=stk[i];
		db ans=sqrt(abs(t))*t*t*t*5.0;
		if(ans>400) printf("f(%d) = MAGNA NIMIS!\n",nowp-i+1);
		else printf("f(%d) = %0.2lf\n",nowp-i+1,ans);
	}
}


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

int main( ) {
   std::vector<double> input( 11 ) , results( 11 ) ;
   for ( int i = 0 ; i < input.size( ) ; i++ )
      std::cin >> input[i];
   cout.precision(2);
   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
	 [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
   for ( int i = 10 ; i > -1 ; i-- ) {
      std::cout << "f(" << input[ i ] << ") = " ;
      if ( results[ i ] > 400 )
	 std::cout << "MAGNA NIMIS!" ;
      else
	 std::cout << fixed << results[ i ];
      std::cout << std::endl ;
   }
   return 0 ;
}


#include <iostream>
#include <array>
#include <cmath>
#include <ioamnip>
using namespace std;

signed main() {
    array<int, 11> a;
    for (int i = 0; i < 11; ++i) {
        cin >> a[i];
    }
    cout << fixed << setprecision(2);
    for (int i = 10; i >= 0; --i) {
        double res = 5 * a[i] * a[i] * a[i] + sqrt(abs(a[i]));
        if (600 >= res) {
            cout << "f(" << a[i] << ") = " << res << '\n';
        } else {
            cout << "f(" << a[i] << ") = " << "MAGNA NIMIS!" << '\n';
        }
    }
    return 0;
}


/*
ID: jonathanh8686
PROG: NAME
LANG: C++11
*/

#include <iostream>
#include <algorithm>
#include <queue>
#include <functional>
#include <stack>
#include <cmath>
#include <vector>
#include <string>
#include <fstream>
#include <iomanip>
#include <set>
#include <map>
#include <bitset>
#include <unordered_map>

#define endl "\n"
#define MAX_INT 2147483647
#define MAX_LONG 18446744073709551615

using namespace std;

ifstream fin("NAME.in");
ofstream fout("NAME.out");

int a[11];
int main()
{
	ios::sync_with_stdio(false);
	for (int i = 0; i < 11; i++)
	{
		cin >> a[i];
	}

	for (int i = 10; i >= 0; i--)
	{
		float ares = sqrt(abs(a[i]));
		float bres = 5 * pow(a[i], 3);

		float res = ares + bres;

		std::cout << std::fixed;
		std::cout << std::setprecision(2);

		if (res <= 400)
		{
			cout << "f(" << a[i] << ") = " << res << endl;
		}
		else
		{
			cout << "f(" << a[i] << ") = MAGNA NIMIS!" << endl;
		}

	}
1
return 0;
}


#warning "too slow"

// [I didn't read the editorial or view any failed test cases]
//
// Idea:
// The prob* v optimal substrufp prot on (i).
// =>
// f(i, t) = set of X values such that
// * initial i+1 station (with station <i have initial val 0, station i have initial val X)
// can be reduced to 0 with
//   + minimal number of trains and
//   + maximal extra cap of last train in time (t)
// (note: the actual set size may be up to 10^9, need compact reptation.)
//
// EDIT: f is not sufficient, a more complex DP function ('k') is required.
// However (I believe) this function's behavior is simple and easily compressible.
//
// Related problems ("simple but hard-to-figure-out DP"):
// 1198D | Rectangle Painting 1; 790D | Bear and Rectangle Strips
//
//
#ifndef LOCAL
#define NDEBUG 1
#endif
#include<bits/stdc++.h>

auto ceildiv(int64_t a,int64_t b){
	assert(a>=0 and b>0);
	return (a+b-1)/b;
}

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

	int nstation,time,trainsize;
	std::cin>>nstation>>time>>trainsize;
	struct station{
		int val,inc,cap;
	};
	std::vector<station> st(nstation);

	int64_t total_inc=0,total_val=0;
	for(auto& [val,inc,cap]:st){
		std::cin>>val>>inc>>cap;
		total_inc+=inc;
		total_val+=val;
	}

	auto const st_back_never_overflow=[&]{ return st.back().val+st.back().inc*(int64_t)time<=st.back().cap; };
	while(not st.empty() and st_back_never_overflow())
		st.pop_back();
	if(st.empty()){
		std::cout<<"0\n";
		return 0;
	}
	// now there must be a moment s.t. values of first (nstation-1) stations are 0
	nstation=(int)st.size();

	std::vector k(nstation,std::vector<std::vector<int64_t>>(time+1));

	// k[i][time][x] = *min* ntrain such that it's possible to get from value (first i == 0, [i] == x)
	// to value (first i = 0, last = x+suminc[0..i]*time-ntrain*trainsize), or INT64_MAX
	//
	// (of course it's also possible to get to state {^} with ntrain=(ntrain+1), as long as
	// x+suminc[0..i]*time-ntrain*trainsize>=0, by appointing another train at time (time))
	//
	// Special case: if ntrain == ceildiv(x+suminc[0..i]*time, trainsize) then it's possible to
	// get from (first i+1 == 0) to (first i+1 == 0, last train have extra
	// (ntrain*trainsize-suminc[0..i]*time-x) cap for next station.

	int64_t suminc_prev=0;
	for(int i=0;
			i<nstation;
			suminc_prev+=st[i].inc,++i){
		auto const [_,lastinc,lastcap]=st[i];
		int64_t const suminc_0i=suminc_prev+lastinc;

		k[i][0].assign(lastcap+1,0); // t=0
		for(int t=1;t<=time;++t){
			k[i][t].resize(lastcap+1); // TODO optimize 'lastcap' (up to 10**9)
			for(int x=0;x<=lastcap;++x){
				auto& cur=k[i][t][x]=INT64_MAX;
				if (x>=trainsize and k[i][t][x-trainsize]!=INT64_MAX)
					cur=k[i][t][x-trainsize]+1; // appoint a train at time 0

				for(int t1=1;t1<=(lastinc==0 ? t : std::min(t,(lastcap-x)/lastinc));++t1){
					// t1: first time after 0 s.t. i first values == 0
					assert(x+lastinc*(int64_t)t1<=lastcap);
					if(i!=0 and k[i-1][t1][0]==INT64_MAX) continue;

					// otherwise it's possible to use ...
					auto ntrain_before_t1=ceildiv(suminc_prev*t1, trainsize);
					// ... trains and have value of [i] at (t1) =
					auto val_i_t1=suminc_0i*t1+x-ntrain_before_t1*trainsize;
					assert(val_i_t1<=x+lastinc*(int64_t)t1);
					assert(val_i_t1>-trainsize);

					if (val_i_t1>=0){
						if(k[i][t-t1][val_i_t1]!=INT64_MAX)
							cur=std::min(cur,ntrain_before_t1+k[i][t-t1][val_i_t1]);
					}else if (t1==t){
						cur=std::min(cur,ntrain_before_t1);
					}
				}
				assert(cur==INT64_MAX or cur<=ceildiv(suminc_0i*time, trainsize));
			}
		}
	}

	std::vector g(nstation,std::vector<char>(time+1));
	// g[i][time] = is it possible to delete just-past first i+1 stations
	// (with max residual cap of last train)?

	suminc_prev=0;
	int64_t sumval_prev=0;
	for(int i=0;
			i<nstation;
			suminc_prev+=st[i].inc,sumval_prev+=st[i].val,++i){
		g[i][0]=true;
		auto const [lastval,lastinc,lastcap]=st[i];
		for(int t=1;t<=time;++t){
			auto& cur=g[i][t];

			for(int t1=0;
					t1<=(lastinc==0 ? t : std::min(t,(lastcap-lastval)/lastinc));
					++t1){
				if(i==0 or g[i-1][t1]){ // t1: first time s.t. first i value = 0
					auto extraval=suminc_prev*t1%trainsize;
					if(extraval!=0) extraval=trainsize-extraval;

					auto curval=lastval+t1*lastinc; // after (t1), before train, at [i]
					assert(curval<=lastcap);

					if (extraval>curval){
						if (t1==t){
							cur=true;
							break;
						}
					}else{
						if (k[i][t-t1][curval-extraval]!=INT64_MAX){
							cur=true;
							break;
						}
					}
				}
			}
		}
	}

	/*
	std::vector gk(nstation,std::vector<int64_t>(time+1));
	// gk: same as k, but initial value of station x (x<=i) is st[x].val instead of 0

	suminc_prev=0;
	sumval_prev=0;
	for(int i=0;
			i<nstation;
			suminc_prev+=st[i].inc,sumval_prev+=st[i].val,++i){
		auto const [_,lastinc,lastcap]=st[i];
		int64_t const suminc_0i=suminc_prev+lastinc;

		gk[i][0]=(sumval_prev+trainsize-1)/trainsize;
		for(int t=1;t<=time;++t){
			auto& cur=gk[i][t];
			cur=INT64_MAX;

			for(int t1=0;t1<t;++t1){ // t1: last time before t s.t. i first values == 0
				if(g[i-1][t-t1] and k[i][t1]!=INT64_MAX){ // TODO should t1 be 'first' or 'last' time?
					auto ntrain_after_t1=(suminc_prev*(t-t1)+trainsize-1)/trainsize;
					//auto extraval_after_t1=(trainsize-1)-(suminc_prev*(t-t1)+trainsize-1)%trainsize;

					auto added_i_after_t1=int64_t(t-t1)*lastinc;
					// (value [i] at t1) + added_i_after_t1 must be <= lastcap
					if(added_i_after_t1>lastcap) continue;

					// assume (y) trains are appointed at time <= (t1) (y >= gk[i][t1]).
					// then (value [i] at t1 (after those y trains are appointed)) = suminc_0i*t1-y*trainsize

					auto min_y=std::max(gk[i][t1],
							(suminc_0i*t1-lastcap+added_i_after_t1+trainsize-1)/trainsize
							);
					assert(min_y>=0);
					assert(suminc_0i*t1-min_y*trainsize+added_i_after_t1<=lastcap);
					if(suminc_0i*t1-min_y*trainsize<0)
						continue;

					cur=std::min(cur,min_y+ntrain_after_t1);
				}
			}
		}
	}
	*/

	std::vector h(nstation,std::vector<int64_t>(time+1));
	// h[i][time] = min # of train required to make sure that (i+1) first stations will
	// not overflow in time (time) with initial value = 0

	suminc_prev=0;
	for(int i=0;
			i<nstation;
			suminc_prev+=st[i].inc,++i){
		h[i][0]=0;
		auto const [_,lastinc,lastcap]=st[i];
		int64_t const suminc_0i=suminc_prev+lastinc;
		for(int t=1;t<=time;++t){
			auto& cur=h[i][t];
			if (lastinc*(int64_t)t<=lastcap){ // [i] will never overflow
				cur=i ? h[i-1][t] : 0;
				continue;
			}
			cur=INT64_MAX;

			for(int t1=1;t1<=t;++t1){
				if(k[i][t1][0]!=INT64_MAX){ // t1: first time >0 s.t. i+1 first value (all values currently crd) == 0
					// (if there's any such time)
					auto ntrain_t1=ceildiv(suminc_0i*t1, trainsize);
					cur=std::min(cur,ntrain_t1+h[i][t-t1]);
				}
			}

			// otherwise if there's no such t1:
			for(int t2=1;t2<=t;++t2){
				if(k[i][t2][0]!=INT64_MAX){
					// t2: last time s.t. i first value (excl. [i]) == 0
					// (Such t2 must exist because value[i] needz to be decreased)

					auto const added_i_after_t2=int64_t(t-t2)*lastinc;
					// (value [i] at t2) + added_i_after_t2 must be <= lastcap
					if(added_i_after_t2>lastcap) continue;

					// assume (y) trains are appointed at time <= (t2) (y >= k[i][t2][0]).
					// then (value [i] at t2 (after those y trains are appointed)) = suminc_0i*t2-y*trainsize
					auto min_y=std::max(k[i][t2][0],
							ceildiv(suminc_0i*t2-lastcap+added_i_after_t2, trainsize)
							);
					assert(min_y>=0);
					assert(suminc_0i*t2-min_y*trainsize+added_i_after_t2<=lastcap);
					if(suminc_0i*t2-min_y*trainsize<0)
						continue;

					cur=std::min(cur,min_y+(i ? h[i-1][t-t2] : 0));
				}
			}

			assert(cur!=INT64_MAX);
		}
	}

	int64_t min_total_ntrain=INT64_MAX;
	for(int t1=0;t1<=time;++t1) // first time s.t. all station value == 0
		if(g[nstation-1][t1])
			min_total_ntrain=std::min(min_total_ntrain,
					ceildiv(total_val+total_inc*t1,trainsize)+h[nstation-1][time-t1]
					);

	// if there's no such t1:
	assert(not st_back_never_overflow());
	for(int t1=0;t1<=time;++t1){ // first time s.t. all station value except last == 0
		auto val_t1_before_train=st.back().val+t1*(int64_t)st.back().inc;
		if(val_t1_before_train<=st.back().cap and (nstation==1 or g[nstation-2][t1])){
			auto const total_val_before_t1=total_val-st.back().val+(total_inc-st.back().inc)*t1;
			auto const ntrain_before_t1=ceildiv(total_val_before_t1,trainsize);
			auto const extracap_t1=ntrain_before_t1*trainsize-total_val_before_t1;
			assert(extracap_t1>=0 and extracap_t1<trainsize);

			auto val_t1=val_t1_before_train-extracap_t1;
			if(val_t1>=0){ // otherwise there exists a time s.t. all station value == 0
				for(int t2=t1;t2<=time;++t2){ // last time s.t. all station value except last == 0
					if(k[nstation-1][t2-t1][val_t1]!=INT64_MAX){
						// assume y = ntrain in time t1..t2.
						// => (val of last at time t2) = val_t1 + total_inc*int64_t(t2-t1) - y*trainsize

						auto const added_last_after_t2=int64_t(time-t2)*st.back().inc;
						// (val of last at time t2) + added_last_after_t2 must be <= st.back().cap
						if(added_last_after_t2>st.back().cap) continue;

						assert(k[nstation-1][t2-t1][val_t1]>=0);
						auto min_y=std::max(
								k[nstation-1][t2-t1][val_t1],
								ceildiv(
									std::max((int64_t)0,
										val_t1+total_inc*int64_t(t2-t1)+added_last_after_t2-st.back().cap),
									trainsize)
								);
						assert(min_y>=0);

						assert(val_t1 + total_inc*int64_t(t2-t1) - min_y*trainsize + added_last_after_t2
								<=st.back().cap);

						if(val_t1 + total_inc*int64_t(t2-t1) - min_y*trainsize<0)
							continue;

						min_total_ntrain=std::min(min_total_ntrain,ntrain_before_t1+min_y+
								(nstation>1 ? h[nstation-2][time-t2] : 0));
					}
				}
			}
		}
	}

	std::cout<<min_total_ntrain<<'\n';
}


#include <bits/stdc++.h>
using namespace std;
const int N = 234;
const long long inf = 1ll << 60;
long long a[N], b[N], c[N], sa[N], sb[N], d[N][N][N], g[N][N][N];
int n, t, k;
int main() {
  freopen("input.txt", "r", stdin);
  cin >> n >> t >> k;
  for (int i = 1; i <= n; ++i)
    cin >> a[i] >> b[i] >> c[i];
  ++n;
  a[n] = c[n] = inf;
  for (int i = 1; i <= n; ++i) {
    sa[i] = sa[i - 1] + a[i];
    sb[i] = sb[i - 1] + b[i];
  }
  for (int p = 1; p <= n; ++p) {
    for (int s = 0; s <= t; ++s) {
      for (int z = 0; z < 2; ++z) {
        d[p][s][z] = g[p][s][z] = inf;
        if (s * b[p] + z * a[p] <= c[p] && d[p - 1][s][z] < inf) {
          d[p][s][z] = d[p - 1][s][z];
          long long value = (z * sa[p - 1] + s * sb[p - 1] + k - 1) / k;
          if (value * k <= z * sa[p] + s * sb[p])
            g[p][s][z] = value;
        }
        for (int r = 0; r < s; ++r) {
          if (g[p][r][z] < inf) {
            long long m = z * sa[p] + r * sb[p] - k * g[p][r][z];
            long long x = (max(m + (s - r) * b[p] - c[p], 0ll) + k - 1) / k;
            if (x * k <= m && d[p - 1][s - r][0] < inf) {
              d[p][s][z] = min(d[p][s][z], g[p][r][z] + x + d[p - 1][s - r][0]);
              long long value = ((s - r) * sb[p - 1] + k - 1) / k;
              if (value * k <= (s - r) * sb[p] + m - x * k)
                g[p][s][z] = min(g[p][s][z], g[p][r][z] + x + value);
            }
          }
        }
      }
    }
  }
  printf("%lld\n", d[n][t][1]);
  return 0;
}


#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <list>
#include <cassert>
#include <ctime>
#include <climits>
using namespace std;

#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
typedef long long ll;
typedef unsigned long long ull;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a%b); }

const int MAXSTAT = 200 + 1; // 1 for dummy station
const int MAXT = 200;

int nstat, tend; ll cap;
ll init[MAXSTAT], delta[MAXSTAT], lim[MAXSTAT];

ll suminit[MAXSTAT + 1], sumdelta[MAXSTAT + 1];

// dp[i][j][x][y] = minimum trains to survive the first i stations for j-x/2 hours (every train being completely full)
// when x==1, there needs to be a train that picked up passengers from the last station in the last hour
// when y==1, include initial number of passengers
ll dp[MAXSTAT + 1][MAXT + 1][2][2];
void upd(ll &a, const ll b) { if (b < a) a = b; }

void run() {
	scanf("%d%d%lld", &nstat, &tend, &cap);
	REP(i, nstat) scanf("%lld%lld%lld", &init[i], &delta[i], &lim[i]);
	//nstat = 200; tend = 200; cap = 1; REP(i, nstat) init[i] = delta[i] = lim[i] = 1000000000;

	init[nstat] = delta[nstat] = cap, lim[nstat] = (tend + 1)*cap, ++nstat; // add dummy station
	suminit[0] = 0; REP(i, nstat) suminit[i + 1] = suminit[i] + init[i];
	sumdelta[0] = 0; REP(i, nstat) sumdelta[i + 1] = sumdelta[i] + delta[i];

	REPE(i, nstat) REPE(j, tend) REP(x, 2) REP(y, 2) dp[i][j][x][y] = LLONG_MAX;
	REPE(j, tend) REP(y, 2) dp[0][j][0][y] = 0;
	REPE(i, nstat) REP(y, 2) dp[i][0][0][y] = 0;
	FORE(i, 1, nstat) FORE(j, 1, tend) REP(y,2) {
		// x=1
		if (y*init[i - 1] + (j - 1)*delta[i - 1] <= lim[i - 1] && dp[i - 1][j - 1][0][y] != LLONG_MAX) { // first train for station i-1
			ll have = y*init[i - 1] + (j - 1)*delta[i - 1], cost = 0; assert(have <= lim[i - 1]);
			ll rembefore = y*suminit[i - 1] + (j - 1)*sumdelta[i - 1] - dp[i - 1][j - 1][0][y] * cap; assert(rembefore >= 0); cost += rembefore / cap + 1;
			ll now = cap*cost - rembefore; assert(now > 0 && now <= cap);
			if (now <= have) upd(dp[i][j][1][y], dp[i - 1][j - 1][0][y] + cost);
		}
		FORE(jj, 1, j - 1) if (dp[i][jj][1][y] != LLONG_MAX && dp[i - 1][j - jj][0][0] != LLONG_MAX) { // previous train for station i-1 at jj-1/2
			ll have = y*suminit[i] + (jj - 1)*sumdelta[i] - dp[i][jj][1][y] * cap; assert(have >= 0 && have <= lim[i - 1]);
			ll dhave = (j - jj)*delta[i - 1], cost1 = 0;
			if (have + dhave > lim[i - 1]) {
				cost1 = (have + dhave - lim[i - 1] + cap - 1) / cap;
				if (cost1*cap > have) continue;
				have -= cost1*cap;
			}
			have += dhave; assert(have <= lim[i - 1]);
			ll rembefore = (j - jj)*sumdelta[i - 1] - dp[i - 1][j - jj][0][0] * cap; assert(rembefore >= 0); ll cost2 = rembefore / cap + 1;
			ll now = cap*cost2 - rembefore; assert(now > 0 && now <= cap);
			if (now <= have) upd(dp[i][j][1][y], dp[i][jj][1][y] + dp[i - 1][j - jj][0][0] + cost1 + cost2);
		}
		// x=0
		if (y*init[i - 1] + j*delta[i - 1] <= lim[i - 1] && dp[i - 1][j][0][y] != LLONG_MAX) { // no trains for station i-1
			//if (i == 1 && j == 3 && y == 1) printf("A%lld\n", dp[i - 1][j][0][y]);
			upd(dp[i][j][0][y], dp[i - 1][j][0][y]);
		}
		FORE(jj, y == 0 ? 2 : 1, j) if (dp[i][jj][1][y] != LLONG_MAX && dp[i][j - jj + 1][0][0] != LONG_MAX) { // previous trains for station i-1 at jj-1/2
			ll have = y*suminit[i] + (jj - 1)*sumdelta[i] - dp[i][jj][1][y] * cap, cost = 0; assert(have >= 0 && have <= lim[i - 1]);
			ll dhave = (j - jj + 1)*delta[i - 1];
			if (have + dhave > lim[i - 1]) {
				ll dcost = (have + dhave - lim[i - 1] + cap - 1) / cap;
				if (dcost*cap > have) continue;
				have -= dcost*cap, cost += dcost;
			}
			have += dhave; assert(have <= lim[i - 1]);
			//if (i == 1 && j == 3 && y == 1) printf("B%lld+%lld+%lld\n", dp[i][jj][1][y], dp[i][j - jj + 1][0][0], cost);
			upd(dp[i][j][0][y], dp[i][jj][1][y] + dp[i][j - jj + 1][0][0] + cost);
		}
	}
	//REPE(i, nstat) REPE(j, tend) { printf("%d,%d:", i, j); REP(x, 2) REP(y, 2) if (dp[i][j][x][y] == LLONG_MAX) printf(" X"); else printf(" %lld", dp[i][j][x][y]); puts(""); }

	ll ans = dp[nstat][tend][0][1];
	printf("%lld\n", ans == LLONG_MAX ? -1 : ans);
}

int main() {
	run();
	return 0;
}


#error "Wrong solution? :("
// <s>Not very rigorously proven...</s>
#ifndef LOCAL
#define NDEBUG
#endif
#include<cassert>
#include<iostream>
#include<vector>

int main(){
	std::ios::sync_with_stdio(0);std::cin.tie(0);
	struct station{
		int val,inc,cap;
	};
	int nstation,time,trainsize;
	std::cin>>nstation>>time>>trainsize;
	std::vector<station> st(nstation);
	for(auto& [val,inc,cap]:st)
		std::cin>>val>>inc>>cap;

	int64_t nstep=0;
	for(int t=0;t<time;++t){
		int last_need_take=-1;
		int last_need_take_now=-1;
		for(unsigned i=0;i<st.size();++i){
			auto const [val,inc,cap]=st[i];
			if(val+inc>cap){
				last_need_take_now=i;
			}
			if(val+inc*int64_t(time-t)>cap)
				last_need_take=i;
		}

		if(last_need_take<0){
			assert(last_need_take_now<0);
			break;
		}

		assert(last_need_take_now<0 or last_need_take_now<=last_need_take);

		for(int i=0;i<=last_need_take;++i){
			auto& [val,inc,cap]=st[i];
			nstep+=val/trainsize; val%=trainsize;

			if(val==0)continue;

			int j=i+1;
			int64_t sumij=val; // [i..j[
			assert(0<sumij and sumij<trainsize);
			while(sumij<trainsize){
				if(j==(int)st.size()){
					// remove all int one step
					if(last_need_take_now<=i and val+inc<=cap){
						// not delete is ok
						goto do_inc; // TODO consider both cases with DP
					}

					// delete all then continue
					++nstep;
					for(unsigned k=i;k<st.size();++k)
						st[k].val=0;
					goto do_inc;
				}
				sumij+=st[j++].val;
			}

			// do one step
			++nstep;
			assert(j>i);
			for(int k=i;k<j-1;++k) st[k].val=0;
			assert(0<=sumij-trainsize and sumij-trainsize<st[j-1].val);
			st[j-1].val=int(sumij-trainsize);
		}
do_inc:

		for(auto& [val,inc,cap]:st){
			val+=inc;
			assert(val<=cap);
		}
	}
	std::cout<<nstep<<'\n';
}


#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <vector>

using namespace std;

typedef long long lint;

struct tarjan_t {
  int n;
  vector<vector<int>> adj;
  vector<int> preorder, inv_preorder;
  stack<int> active;
  vector<bool> is_active;
  vector<int> cnt_of;
  vector<vector<int>> cnts;
  tarjan_t(int _n)
      : n(_n)
      , adj(n)
      , inv_preorder(n, -1)
      , is_active(n, false)
      , cnt_of(n, -1) {}
  int dfs(int v) {
    inv_preorder[v] = preorder.size();
    preorder.push_back(v);
    active.push(v);
    is_active[v] = true;
    int highest = inv_preorder[v];
    for (int u : adj[v]) {
      if (inv_preorder[u] == -1)
        highest = max(highest, dfs(u));
      else if (is_active[u])
        highest = max(highest, inv_preorder[u]);
    }
    if (highest == inv_preorder[v]) {
      int u;
      vector<int> cnt;
      do {
        u = active.top();
        active.pop();
        is_active[u] = false;
        cnt_of[u] = cnts.size();
        cnt.push_back(u);
      } while (u != v);
      cnts.push_back(move(cnt));
    }
    return highest;
  }
  void solve() {
    for (int i = 0; i < n; ++i)
      if (inv_preorder[i] == -1)
        dfs(i);
  }
};

struct twosat_t {
  int n;
  vector<vector<int>> adj;
  twosat_t() {}
  twosat_t(int _n): n(_n), adj(2 * n) {}
  bool solve() {
    tarjan_t tarjan(2 * n);
    tarjan.adj = adj;
    tarjan.solve();
    for (int i = 0; i < n; ++i)
      if (tarjan.cnt_of[2 * i + 0] == tarjan.cnt_of[2 * i + 1])
        return false;
    return true;
  }
  void add_or(int a, int b) {
    adj[a ^ 1].push_back(b);
    adj[b ^ 1].push_back(a);
  }
  void set(int a) {
    adj[a ^ 1].push_back(a);
  }
};

enum op_t { AND = 0, OR, NAND, NOR, NONE };

int apply(op_t op, int a, int b) {
  switch (op) {
  case AND: return a & b;
  case OR: return a | b;
  case NAND: return !(a & b);
  case NOR: return !(a | b);
  default: return -1;
  }
}

op_t mirror(op_t op) {
  switch (op) {
  case AND: return OR;
  case NAND: return NOR;
  case OR: return AND;
  case NOR: return NAND;
  default: return NONE;
  }
}

struct gate_t {
  int id = -1;
  op_t op = NONE;
  gate_t *left = nullptr, *right = nullptr;
  int enforce_value = -1;
  gate_t() {}
  gate_t(int _id): id(_id) {}
  gate_t(op_t _op, gate_t *_left, gate_t *_right)
      : op(_op), left(_left), right(_right) {}
  int regular() {
    if (enforce_value != -1) return enforce_value;
    assert(id == -1);
    return apply(op, left->regular(), right->regular());
  }
  int other() {
    if (enforce_value != -1) return enforce_value;
    assert(id == -1);
    return apply(mirror(op), left->regular(), right->regular());
  }
  void add_constraints(int target, twosat_t &twosat) {
    int a = left->id, b = right->id;
    op_t eff_op = op;
    if (eff_op == NAND) {
      eff_op = AND;
      target ^= 1;
    }
    if (eff_op == NOR) {
      eff_op = OR;
      target ^= 1;
    }
    if (eff_op == AND) {
      if (target == 0) twosat.add_or(2 * a + 0, 2 * b + 0);
      else {
        twosat.set(2 * a + 1);
        twosat.set(2 * b + 1);
      }
    } else if (eff_op == OR) {
      if (target == 0) {
        twosat.set(2 * a + 0);
        twosat.set(2 * b + 0);
      } else {
        twosat.add_or(2 * a + 1, 2 * b + 1);
      }
    } else assert(0);
  }
};

string read_string() {
  char *str;
  scanf("%ms", &str);
  string result(str);
  free(str);
  return result;
}

op_t read_op() {
  string s = read_string();
  if (s == "and") return AND;
  if (s == "or") return OR;
  if (s == "nand") return NAND;
  if (s == "nor") return NOR;
  return NONE;
}

vector<int> read_ids() {
  string s = read_string();
  vector<int> ids;
  for (int i = 0; i < (int)s.size(); ++i)
    if (s[i] == 'x')
      ids.push_back(i);
  return ids;
}

int main() {
  int ni, n1, n2;
  scanf("%d %d %d", &ni, &n1, &n2);
  vector<gate_t> input(ni);
  for (int i = 0; i < ni; ++i)
    input[i] = {i};
  vector<gate_t> l1(n1);
  for (int i = 0; i < n1; ++i) {
    op_t op = read_op();
    vector<int> ids = read_ids();
    l1[i] = {op, &input[ids[0]], &input[ids[1]]};
  }
  vector<gate_t> l2(n2);
  for (int i = 0; i < n2; ++i) {
    op_t op = read_op();
    vector<int> ids = read_ids();
    l2[i] = {op, &l1[ids[0]], &l1[ids[1]]};
  }

  vector<vector<int>> adj(n2);
  vector<bool> removed(n2, false);
  for (int i = 0; i < n2; ++i)
    for (int j = i; j < n2; ++j) {
      vector<int> ids;
      for (int k : {i, j})
        for (auto child1 : {&gate_t::left, &gate_t::right})
          for (auto child2 : {&gate_t::left, &gate_t::right})
            ids.push_back((l2[k].*child1->*child2)->id);
      sort(ids.begin(), ids.end());
      ids.resize(unique(ids.begin(), ids.end()) - ids.begin());
      bool conflict = false;
      for (int mask = 0; mask < (1<<(int)ids.size()); ++mask) {
        for (int k = 0; k < (int)ids.size(); ++k)
          input[ids[k]].enforce_value = ((mask & (1<<k)) != 0);
        int regular = l2[i].regular() | l2[j].regular();
        int other = l2[i].other() | l2[j].other();
        if (regular && other)
          conflict = true;
      }
      for (int k = 0; k < (int)ids.size(); ++k)
        input[ids[k]].enforce_value = -1;
      if (conflict) {
        if (i == j) removed[i] = true;
        else {
          adj[i].push_back(j);
          adj[j].push_back(i);
        }
      }
    }

  vector<bool> mark(n2, false);
  vector<int> left_side, right_side;
  for (int i = 0; i < n2; ++i) {
    if (!removed[i] && !mark[i]) {
      vector<int> side0, side1;
      function<void(int, int)> dfs = [&](int v, int s) {
        mark[v] = true;
        if (s == 0) side0.push_back(v);
        else side1.push_back(v);
        for (int u : adj[v])
          if (!removed[u] && !mark[u])
            dfs(u, s ^ 1);
      };
      dfs(i, 0);
      if (side0.size() > side1.size()) swap(side0, side1);
      left_side.insert(left_side.end(), side0.begin(), side0.end());
      right_side.insert(right_side.end(), side1.begin(), side1.end());
    }
  }

  const int nleft = left_side.size(), nright = right_side.size();
  vector<lint> left_adj_mask(nleft);
  for (int i = 0; i < nleft; ++i) {
    int v = left_side[i];
    for (int u : adj[v])
      if (!removed[u]) {
        int j =
            find(right_side.begin(), right_side.end(), u) - right_side.begin();
        assert(j < nright);
        left_adj_mask[i] |= 1LL<<j;
      }
  }
  const int half1 = nleft / 2, half2 = (nleft + 1) / 2;
  vector<lint> half1_mask(1<<half1), half2_mask(1<<half2);
  for (int i = 0; i < half1; ++i) half1_mask[1 << i] = left_adj_mask[i];
  for (int i = 0; i < half2; ++i) half2_mask[1 << i] = left_adj_mask[i + half1];
  for (vector<lint> &half_mask : {ref(half1_mask), ref(half2_mask)}) {
    for (int i = 1; i < (int)half_mask.size(); ++i) {
      int low_bit = i&-i;
      half_mask[i] |= half_mask[low_bit];
      half_mask[i] |= half_mask[i ^ low_bit];
    }
  }

  int max_keep = -1;
  const bool ensure_maximal = (nright <= 29);
  vector<bool> visited_right;
  if (ensure_maximal) visited_right.resize(1<<nright, false);
  for (int left_mask = (1<<nleft) - 1; left_mask >= 0; --left_mask) {
    lint adj_right_mask = half1_mask[((1 << half1) - 1) & left_mask] |
                          half2_mask[left_mask >> half1];
    lint right_mask = ((1LL<<nright) - 1) ^ adj_right_mask;
    if (ensure_maximal) {
      if (visited_right[right_mask]) continue;
      visited_right[right_mask] = true;
    }
    vector<int> cands;
    for (int i = 0; i < nleft; ++i) if (left_mask & (1<<i)) cands.push_back(i);
    for (int i = 0; i < nright; ++i)
      if (right_mask & (1LL<<i))
        cands.push_back(i);
    twosat_t twosat(ni);
    for (int c : cands) {
      gate_t &gate = l2[c];
      gate_t *subs[2] = {gate.left, gate.right};
      vector<int> notrigger_masks;
      for (int mask = 0; mask < (1<<2); ++mask) {
        for (int k = 0; k < 2; ++k)
          subs[k]->enforce_value = ((mask & (1 << k)) != 0);
        bool trigger = gate.regular() || gate.other();
        if (!trigger) notrigger_masks.push_back(mask);
      }
      for (int k = 0; k < 2; ++k) subs[k]->enforce_value = -1;
      if (notrigger_masks.size() == 1) {
        for (int k = 0; k < 2; ++k)
          subs[k]->add_constraints(((notrigger_masks[0] & (1<<k)) != 0), twosat);
      }
    }
    if (!twosat.solve()) max_keep = max(max_keep, (int)cands.size());
  }

  int result;
  if (max_keep == -1) result = -1;
  else result = l2.size() - max_keep;
  printf("%d\n", result);

  return 0;
}


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

struct Gate {
  int kind,x,y;
  Gate() {}
  Gate(int a,int b,int c):kind(a),x(b),y(c) {}
};

Gate a[55];

bool in[55];

int calc(Gate t,int n) {
  memset(in,0,sizeof(in));
  in[a[t.x].x]=in[a[t.x].y]=1;
  in[a[t.y].x]=in[a[t.y].y]=1;
  int cnt=0;
  for(int i=1;i<=n;i++) cnt+=in[i];
  int x=t.kind,y=a[t.x].kind,z=a[t.y].kind;
  if (cnt==2) {
  	if (x==1&&y==1&&z==3) return 1;
  	if (x==1&&y==3&&z==1) return 1;
  	if (x==3&&y==1&&z==3) return 3;
  	if (x==3&&y==3&&z==1) return 3;
  	if (x==1&&y==2&&z==4) return 1;
  	if (x==1&&y==4&&z==2) return 1;
  	if (x==3&&y==2&&z==4) return 3;
  	if (x==3&&y==4&&z==2) return 3;
  	if (x==4&&y==1&&z==3) return 1;
  	if (x==4&&y==3&&z==1) return 1;
  	if (x==2&&y==1&&z==3) return 3;
  	if (x==2&&y==3&&z==1) return 3;
  	if (x==4&&y==2&&z==4) return 1;
  	if (x==4&&y==4&&z==2) return 1;
  	if (x==2&&y==2&&z==4) return 3;
  	if (x==2&&y==4&&z==2) return 3;
  	if (x==1&&y==1&&z==4) return 2;
  	if (x==1&&y==4&&z==1) return 2;
  	if (x==3&&y==3&&z==2) return 4;
  	if (x==3&&y==2&&z==3) return 4;
  	if (x==4&&y==3&&z==2) return 2;
  	if (x==4&&y==2&&z==3) return 2;
  	if (x==2&&y==1&&z==4) return 4;
  	if (x==2&&y==4&&z==1) return 4;
  }
  else if (cnt==3) {
  	if (x==1&&y==1&&z==4) return 2;
  	if (x==1&&y==4&&z==1) return 2;
  	if (x==3&&y==3&&z==2) return 4;
  	if (x==3&&y==2&&z==3) return 4;
  }
  return 0;
}

char str[100];

Gate read() {
  scanf("%s",str+1);
  Gate now;
  if (str[1]=='a') now.kind=1;
  else if (str[1]=='o') now.kind=2;
  else if (str[2]=='a') now.kind=3;
  else now.kind=4;
  scanf("%s",str+1);
  int len=strlen(str+1);
  for(int i=1;i<=len;i++)
    if (str[i]=='x') {
	  now.x=i;
	  break;
    }
  for(int i=now.x+1;i<=len;i++)
    if (str[i]=='x') {
    	now.y=i;
    	break;
	}
  return now;
}

int cnt[5];

int main() {
  int n,m,k;
  scanf("%d%d%d",&n,&m,&k);
  for(int i=1;i<=m;i++) a[i]=read();
  for(int i=1;i<=k;i++) {
  	Gate x=read();
  	int t=calc(x,n);
  	cnt[t]++;
  }
  int ans=0;
  if (cnt[1]) ans=max(ans,cnt[1]+cnt[2]);
  if (cnt[3]) ans=max(ans,cnt[3]+cnt[4]);
  printf("%d\n",(ans)?k-ans:-1);
  return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <cstdio>
#include <stdlib.h>
#include <stack>
#include <numeric>
#include <bitset>
#include <cctype>
#include <list>
#include <assert.h>
#include <random>
#include <unordered_map>
#include <ctime>
typedef  long long ll;
using namespace std;
#define INF 2147483647
#define infL (1LL<<60)
#define inf (1<<30)
#define inf9 (1000000000)
#define MOD 1000000007
#define EPS 1e-9
#define Gr 9.8
#define PI acos(-1)
#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define REQ(i,n) for(int (i)=1;(i)<=(int)(n);(i)++)
#define lch (rt<<1)
#define rch (rt<<1|1)
#define readmp(n) for(int i=0,u,v;i<n;i++) {scanf("%d%d",&u,&v); mp[u].push_back(v); mp[v].push_back(u);}
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;
template<typename  T> void maxtt(T& t1, T t2) {
    t1=max(t1,t2);
}
template<typename  T> void mintt(T& t1, T t2) {
    t1=min(t1,t2);
}
#define MAX 105

bool debug = 0;
int n,m,k;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
string direc="RDLU";
ll ln, lk, lm;
void etp(bool f = 0) {
    puts(f ?"YES" : "NO");
    exit(0);
}
void addmod(int &x, int y, int mod = MOD) {
    assert(y>=0);
    x+=y; if (x>=mod) x-=mod;
    assert(x>=0 && x<mod);
}
void et(int x=-1) {
    printf("%d\n", x); exit(0);
}
ll fastPow(ll x, ll y, int mod=MOD) {
    ll ans = 1;
    while(y>0) {
        if(y&1) ans = (x * ans)%mod;
        x = x*x%mod;
        y>>=1;
    }
    return ans;
}
ll gcd1(ll x, ll y) { return y?gcd1(y,x%y):x;}

struct yq {
    string ope;
    bool smV = false;
    int a,b;
    void rd(int n) {
        string tmp; cin>>ope>>tmp;
        a=0;b=0;
        REP(i,n) if (tmp[i]=='x') {
            if(a==0) a=i+1; else b=i+1;
        }
    }
}l3[55], l2[55];
bool isSpa(yq &x, yq &y) {
    return x.a==y.a&&x.b==y.b;
}
bool isCpa(yq &x, yq &y) {
    return x.a==y.a||x.a==y.b ||x.b==y.a||x.b==y.b;
}
int getType(yq &o) {
    yq c1=l3[o.a], c2=l3[o.b];
    if (!o.smV) {
        if (!isCpa(c1, c2)) return -1;
        if (o.ope=="and") {
            if (c1.ope=="and" && c2.ope=="nor") return 0;
            if (c2.ope=="and" && c1.ope=="nor") return 0;
        }
        return -1;
    }

    if (o.ope=="and") {
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        swap(c1,c2);
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
    } else if (o.ope=="nor") {
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        if (c1.ope=="nand" && c2.ope=="or") return 0;
        swap(c1,c2);
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        if (c1.ope=="nand" && c2.ope=="or") return 0;
    }
    return -1;
}
int getType2(yq &o) {
    yq c1=l3[o.a], c2=l3[o.b];
    if (!o.smV) {
        if (!isCpa(c1, c2)) return -1;
        if (o.ope=="or") {
            if (c1.ope=="and" && c2.ope=="nor") return 0;
            if (c2.ope=="and" && c1.ope=="nor") return 0;
        }
        return -1;
    }
    if (o.ope=="or") {
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        swap(c1,c2);
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
    } else if (o.ope=="nand") {
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        if (c1.ope=="nand" && c2.ope=="or") return 0;
        swap(c1,c2);
        if (c1.ope=="and" && c2.ope=="nand") return 1;
        if (c1.ope=="or" && c2.ope=="nor") return 1;
        if (c1.ope=="nand" && c2.ope=="or") return 0;
    }
    return -1;
}
int ans=-1,cc[2];
void fmain(int ID) {
    scanf("%d%d%d", &k, &n, &m);
    REQ(i,n) l3[i].rd(k);
    REQ(i,m) l2[i].rd(n);

    REP(i,2)cc[i]=0;
    REQ(i,m) {
        l2[i].smV = isSpa(l3[l2[i].a], l3[l2[i].b]);
        int z=getType(l2[i]);
        if (z!=-1) cc[z]++;
    }
    if (cc[1]) ans=cc[0]+cc[1];
    //rev
    REP(i,2)cc[i]=0;
    REQ(i,m) {
        int z=getType2(l2[i]);
        if (z!=-1) cc[z]++;
    }
    if (cc[1]) maxtt(ans, cc[0]+cc[1]);
    if (ans!=-1) ans=m-ans;
    printf("%d\n", ans);
}

int main() {
    int t=1;
//    scanf("%d", &t);
    REQ(i,t) {
        fmain(i);
    }
    return 0;
}


#include <bits/stdc++.h>

#define F0R(i, a) for(int i = 0; i < (a); i++)
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define R0F(i, a) for(int i = (a) - 1; i >= 0; i--)
#define ROF(i, a, b) for(int i = (b) - 1; i >= (a); i--)

#define ran() (rand() & 0x7FFF)
#define rand31() ((ran() << 16) | (ran() << 1) | (ran() & 1))
#define rand32() ((ran() << 17) | (ran() << 2) | (ran() & 3))
#define rand63() (((ll)ran() << 48) | ((ll)ran() << 33) | ((ll)ran() << 18) | ((ll)ran() << 3) | ((ll)ran() & 7))
#define rand64() (((ll)ran() << 49) | ((ll)ran() << 34) | ((ll)ran() << 19) | ((ll)ran() << 4) | ((ll)ran() & 15))

#define F first
#define S second
#define PB push_back
#define MP make_pair
#define MT make_tuple
#define UB upper_bound
#define LB lower_bound
#define X real()
#define Y imag()

#define PI acos(-1)

#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define SQ(x) ((x) * (x))

using namespace std;

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<ull> vul;
typedef complex<ld> point;
typedef complex<ld> cld;
typedef vector<cld> vcld;

struct op {
    string ot;
    int conn1, conn2;
    int getConn(int idx) { return idx?conn2:conn1; }
};

int n, m, k;
int val[2][50];
vector<op> ops[2];
bool occ[50][4];

string neg(string ot) {
    if (ot[0] == 'n') return ot.substr(1, sz(ot) - 1);
    return "n" + ot;
}

int apply(string ot, int b1, int b2, bool flip=false) {
    if (flip) ot = neg(ot);
    if (ot == "and") return b1 & b2;
    if (ot == "or") return b1 | b2;
    if (ot == "nand") return 1 ^ (b1 & b2);
    if (ot == "nor") return 1 ^ (b1 | b2);
}

op readOp(int connlen) {
   string ot, conns;
   cin >> ot >> conns;
   vi v;
   F0R(i, n) if(conns[i] == 'x') v.PB(i);
   return {ot, v[0], v[1]};
}

int eval(int idx, bool flip) {
    F0R(i, 2) {
        int opidx = ops[1][idx].getConn(i);
        op o = ops[0][opidx];
        val[1][opidx] = apply(o.ot, val[0][o.conn1], val[0][o.conn2], flip);
    }
    op o = ops[1][idx];
    return apply(o.ot, val[1][o.conn1], val[1][o.conn2], flip);
}

int main() {
    ios::sync_with_stdio(0);
	cin.tie(0);
    cin >> n >> m >> k;
    F0R(i, m) ops[0].PB(readOp(n));
    F0R(i, k) ops[1].PB(readOp(m));
    bool has[2]{0, 0};
    int cnt[2]{0, 0};
    F0R(i, k) {
        set<int> inps;
        F0R(a, 2) F0R(b, 2) inps.insert(ops[0][ops[1][i].getConn(a)].getConn(b));
        vi v(all(inps));
        F0R(mask, 1 << sz(v)) {
            F0R(j, sz(v)) val[0][v[j]] = (mask >> j) & 1;
            occ[i][(eval(i, false) << 1) | eval(i, true)] = 1;
        }
        if (occ[i][3]) continue;
        if (occ[i][1]) {
            cnt[0]++;
            if (!occ[i][0]) has[0] = 1;
        }
        if (occ[i][2]) {
            cnt[1]++;
            if (!occ[i][0]) has[1] = 1;
        }
    }
    int res = 0;
    F0R(i, 2) if (has[i]) res = max(res, cnt[i]);
    if (res == 0) cout << -1 << endl;
    else cout << k - res << endl;
}


#include<bits/stdc++.h>
#define inf 0x7f7f7f7f
int l,Test_num,mxc,mxx;
char ch[53];
int f[53][53][511][2];
int dp(int pos,int c,int x,int delta)
{
	if(pos==l) return c?inf:0;
	if(c>mxc||c<-mxc||x>mxx||x<-mxx) return inf;
	if(!(~f[pos][c+mxc][x+mxx][(delta==1)]))
	{
	    f[pos][c+mxc][x+mxx][(delta==1)]=min(dp(pos,c,x+delta,delta)+l-pos,min(dp(pos+1,c*10+ch[pos+1]-x,x,1),dp(pos+1,c*10+ch[pos+1]-x,x,-1)));
	}
	return f[pos][c+mxc][x+mxx][(delta==1)];
}
int main()
{
	scanf("%s",ch+2);
	l=strlen(ch+2)+1;
	ch[1]=0;
	mxx=5*l;
	mxc=mxx/10+1;
	for(int i=2;i<=l;i++)
	{
	    ch[i]^=48;
	}
	memset(f,-1,sizeof(f));
	printf("%d",dp(0,0,0,1));
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")

#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define md(l, r) l + (r - l) / 2
#define ll long long
#define btw(a, l, r) a.begin() + l, a.begin() + r + 1
#define F first
#define S second
#define pb push_back
#define all(x) x.begin(), x.end()
#define sz(x) (int(x.size()))
#define sqr(x) (x) * (x)
#define endl '\n'

#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define clr(x, y) memset((x), (y), sizeof (x))
#define ld long double
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<vector<pair<int, int> > > vvpii;
typedef vector<vector<pair<ll, ll> > > vvpll;
typedef pair<int, pair<int, int> > piii;
typedef vector<ll> vll;
typedef vector<pair<int, int> > vpii;
typedef vector<pair<ll, ll> > vpll;
typedef vector<vector<ll> > vvll;
typedef vector<pair<ll, pair<ll, ll> > > vplll;
typedef pair<ll, ll> pll;

const ld eps = -1e9;
const long long N = 200001, P = 1e9 + 7, P1 = 1e9 + 13, iINF = 1e9, INF = 2e18, K = 73, K1 = 79;

ll dstF(ll x, ll y, ll xx, ll yy) {
    return (sqr(x - xx) + sqr(y - yy));
}

ld dstSqrtF(ll x, ll y, ll xx, ll yy) {
    return (sqrt(sqr(x - xx) + sqr(y - yy)));
}

ll _bp(ll val, ll st, ll p) {
    if (st == 0) {
        return 1;
    }
    ll temp = _bp(val, st / 2, p);
    temp = sqr(temp);
    temp %= p;
    if (st % 2 == 1) {
        temp *= val;
        temp %= p;
    }
    return temp;
}

ll _bp(ll val, ll st) {
    if (st == 0) {
        return 1;
    }
    ll temp = _bp(val, st / 2);
    temp = sqr(temp);
    if (st % 2 == 1) {
        temp *= val;
    }
    return temp;
}

ll nok(ll a, ll b) {
    return (a / __gcd(a, b) * b);
}

#define int long long

int n, ans = 1e18;
int st[100], dp[100];

void solve() {
    cin >> n;
    int n1 = n;
    int k = 0;
    while (n1 != 0) {
        k++;
        n1 /= 10;
    }
    int tp = n;
    st[0] = 1;
    for (int i = 1; i <= k; i++) {
        st[i] = st[i - 1] * 10;
    }
    while (dp[0] == 0) {
        int curVal = 0;
        n = tp;
        for (int i = 1; i < k; i++) {
            int x = (n / st[k - i]);
            int y = x;
            if (x * ((st[k - i + 1] - 1) / 9) >= n) {
                y--;
            } else {
                y++;
            }
            z = max(x, y) + 1;
            if (dp[i] == 0) {
                n -= x * ((st[k - i + 1] - 1) / 9);
                curVal += x * (k - i + 1);
            } else {
                n -= max(0ll, y) * ((st[k - i + 1] - 1) / 9);
                curVal += y * (k - i + 1);
            } else {
                n -= max(0ll, z) * ((st[k - i + 1] - 1) / 9);
                curVal += z * (k - i + 1);
            }
            n = abs(n);
        }
        curVal += n;
        ans = min(ans, curVal);
        int p = k;
        while (dp[p] == 2) {
            dp[p] = 0;
            --p;
        }
        dp[p]++;
    }
    cout << ans;
}

signed main() {
    fast_io;
    int q;
    q = 1;
    //cin >> q;
    while (q != 0) {
        solve();
        --q;
    }
}


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

#include <bits/stdc++.h>

// #include <atcoder/all>

using namespace std;
// using namespace atcoder;

#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define DEBUG_VEC(v) cerr<<#v<<":";for(int i=0;i<v.size();i++) cerr<<" "<<v[i]; cerr<<endl;
#define DEBUG_MAT(v) cerr<<#v<<endl;for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++) {cerr<<v[i][j]<<" ";}cerr<<endl;}
typedef long long ll;
// #define int ll

#define vi vector<int>
#define vl vector<ll>
#define vii vector< vector<int> >
#define vll vector< vector<ll> >
#define vs vector<string>
#define pii pair<int,int>
#define pis pair<int,string>
#define psi pair<string,int>
#define pll pair<ll,ll>
template<class S, class T> pair<S, T> operator+(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first + t.first, s.second + t.second); }
template<class S, class T> pair<S, T> operator-(const pair<S, T> &s, const pair<S, T> &t) { return pair<S, T>(s.first - t.first, s.second - t.second); }
template<class S, class T> ostream& operator<<(ostream& os, pair<S, T> p) { os << "(" << p.first << ", " << p.second << ")"; return os; }
#define X first
#define Y second
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define rrep1(i,n) for(int i=(int)(n);i>0;i--)
#define REP(i,a,b) for(int i=a;i<b;i++)
#define in(x, a, b) (a <= x && x < b)
#define all(c) c.begin(),c.end()
void YES(bool t=true) {cout<<(t?"YES":"NO")<<endl;}
void Yes(bool t=true) {cout<<(t?"Yes":"No")<<endl;}
void yes(bool t=true) {cout<<(t?"yes":"no")<<endl;}
void NO(bool t=true) {cout<<(t?"NO":"YES")<<endl;}
void No(bool t=true) {cout<<(t?"No":"Yes")<<endl;}
void no(bool t=true) {cout<<(t?"no":"yes")<<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; }
#define UNIQUE(v) v.erase(std::unique(v.begin(), v.end()), v.end());
const ll inf = 1000000001;
const ll INF = (ll)1e18 + 1;
const long double pi = 3.1415926535897932384626433832795028841971L;
int popcount(ll t) { return __builtin_popcountll(t); }
// int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
// int dx2[8] = { 1,1,0,-1,-1,-1,0,1 }, dy2[8] = { 0,1,1,1,0,-1,-1,-1 };
vi dx = {0, 1, 0, -1}, dy = {-1, 0, 1, 0};
// vi dx2 = { 1,1,0,-1,-1,-1,0,1 }, dy2 = { 0,1,1,1,0,-1,-1,-1 };
struct Setup_io {
    Setup_io() {
        ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
        cout << fixed << setprecision(25);
    }
} setup_io;
const ll MOD = 1000000007;
// const ll MOD = 998244353;
// #define mp make_pair
//#define endl '\n'

const int N = 50, M = 270, K = 60;
const int offset = 30;
int dp[2][M][M][K];
array<int, 4> pre[N + 1][M][M][K];

int carry(int x) {
    if (x >= 0) return x / 10 + offset;
    else if (x % 10 != 0) return x / 10 - 1 + offset;
    else return x / 10 + offset;
}

signed main() {
    string s;
    cin >> s;
    s = "000"s + s;
    int n = s.size();

    rep (j, M) rep (k, M) rep (c, K) dp[0][j][k][c] = inf;
    rep (j, M) rep (k, M) {
        int x = j - k;
        int d = (x % 10 + 10) % 10;
        if (s.back() - '0' == d) {
            dp[0][j][k][carry(x)] = j + k;
        }
    }

    int now = 0, nex = 1;
    for (int i = n - 2; i >= 0; i--) {
        rep (j, M) rep (k, M) rep (c, K) {
            dp[nex][j][k][c] = inf;
        }

        rep (j, M) rep (k, M) rep (C, K) {
            if (dp[now][j][k][C] == inf) continue;
            int c = C - offset;

            for (int d = 0; d < 10; d++) {
                int nj = j - d;
                if (nj < 0) break;
                int nk = k;
                int x = nj - nk + c;
                int y = (x % 10 + 10) % 10;
                if (s[i] - '0' == y) {
                    if (chmin(dp[nex][nj][nk][carry(x)], dp[now][j][k][C] + nj + nk)) {
                        pre[nex][nj][nk][carry(x)] = {now, j, k, C};
                    }
                }
            }

            for (int d = 1; d < 10; d++) {
                int nj = j;
                int nk = k - d;
                if (nk < 0) break;
                int x = nj - nk + c;
                int y = (x % 10 + 10) % 10;
                if (s[i] - '0' == y) {
                    if (chmin(dp[nex][nj][nk][carry(x)], dp[now][j][k][C] + nj + nk)) {
                        pre[nex][nj][nk][carry(x)] = {now, j, k, C};
                    }
                }
            }
        }
        swap(now, nex);
        // now++; nex++;
    }

    cout << dp[now][0][0][offset] << endl;
}


#pragma GCC optimize "O3"
#include<bits/stdc++.h>
using namespace std;

#define sz(s) (int)s.size()
#define f first
#define s second
#define pb push_back
#define all(s) s.begin(), s.end()

#define vi vector<int>
#define vvi vector<vi>
#define ll long long
#define ull unsigned ll
#define vll vector<ll>

#define ii pair<int, int>
#define vii vector<ii>
#define vvii vector<vii>

const int INF = 1e9 + 7;
const int mod = 998244353;
// const int N = 1e6 + 7;
const int T = 1 << 20;
#define ld long double

template<class T, class G> ostream & operator << (ostream&os, const pair<T, G> & para) { os << para.first << ' ' << para.second; return os; }
template<class T> ostream & operator << (ostream&os, const vector<T> & vec){ for(const auto & el : vec) os << el << ' '; return os; }

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define losuj(a, b) uniform_int_distribution<long long>(a, b)(rng)

short dp[51][251][251][101];

void solve(){
    for(int i = 0; i <= 50; i++)
        for(int j = 0; j <= 250; j++)
            for(int a = 0; a <= 250; a++)
                for(int b = 0; b <= 100; b++)
                    dp[i][j][a][b] = 20000;
    dp[0][250][250][0] = 0;

    string s;
    cin >> s;
    reverse(all(s));
    int n = sz(s);

    for(int i = 0; i <= n; i++)
        for(int carry = 0; carry <= 100; carry++)
            for(int a = 250; a >= 0; a--)
                for(int b = 250; b >= 0; b--){
                    if(a < 250)
                        dp[i][a][b][carry] = min(dp[i][a][b][carry], dp[i][a + 1][b][carry]);
                    if(b < 250)
                        dp[i][a][b][carry] = min(dp[i][a][b][carry], dp[i][a][b + 1][carry]);

                    if(i == sz(s))
                        continue;
                    int sum_bit = (a - b + carry - (s[i] - '0'));
                    int new_carry = sum_bit / 10;
                    if(sum_bit % 10 == 0 and sum_bit >= 0)
                        dp[i + 1][a][b][new_carry] = min(dp[i + 1][a][b][new_carry], dp[i][a][b][carry] + a + b);
                }

    cout << dp[n][0][0][0] << '\n';
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    // prep();
    int test = 1;
    // cin >> test;

    for(int i = 0; i < test; i++)
        solve();
}


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

int A[1000001];
int N;

bool brute(int i, int j, bool go) {
	if(i >= j) return true;
	if((j - i)%2) return false;
	int a = A[i];
	if(a < 0) return false;
	for(int k = i + 1; k < j; k++) {
		if(A[k] == a || A[k] == -a) {
			if(brute(i + 1, k, false) && brute(k + 1, j, false)) {
				if(go) {
					A[k] = -a;
					brute(i + 1, k, true);
					brute(i + 1, j, true);
				}
				return true;
			}
		}
	}
	return false;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin >> N;
	for(int i=0;i<N;i++) cin >> A[i];
	int q; cin >> q;
	while(q--) { int k; cin >> k; A[k] = -A[k]; }

	if(brute(0, N, true)) {
		for(int i=0;i<N;i++) printf("%d%c", A[i], ((i+1)==N)?'\n':' ');
	}
	else {
		printf("-1\n");
	}
}


#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <cmath>
#include <cstdlib>
#include <locale>
#include <map>
#include <functional>
#include <utility>
using namespace std;
#define MS0(I) memset(I, 0, sizeof(I));
#define MS1(I) memset(I, -1, sizeof(I));
#define rep(i, n) for(int i = 0; i < (n); ++i)
#define rep1(i, s, n) for(int i = (s); i < (n); ++i)
#define pb push_back
#define ALL(I) (I).begin(), (I).end()
#define MAX 1000005
#define F first
#define S second
typedef const void CV;
typedef long long LL;
typedef unsigned long long ULL;
int store[MAX];
vector<int>trace;
int main(void){
    int n; scanf("%d", &n);
    rep1(i, 1, n+1) scanf("%d", store + i);
    int t; scanf("%d", &t);
    rep(i, t){
        int v; scanf("%d", &v);
        store[v] = -store[v];
    }
    for(int i = n; i >= 1; i--){
        if(trace.empty()){
            if(store[i] > 0){
                store[i] = -store[i];
                trace.pb(store[i]);
            }
            else trace.pb(store[i]);
        }
        else{
            if(store[i] > 0){
                if(store[i] == -trace.top()) trace.pop();
                else{
                    store[i] = -store[i];
                    trace.pb(store[i]);
                }
            }
            else{
                trace.pb(store[i]);
            }
        }
    }
    if(trace.empty()){
        puts("YES");
        rep1(i, 1, n+1) printf("%d ", store[i]);
    }
    else puts("NO");
    return 0;
}


#include <iostream>
#include <cstdio>
#include <stack>
#define MAXN 1000005

using namespace std;

int n, a[MAXN], next[MAXN], prev[MAXN];

main()
{
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", a + i);
  int m, x;
  scanf("%d", &m);
  for (int i = 0; i < m; i++)
    {
      scanf("%d", &x);
      a[x] = - a[x];
    }

  stack<int> s, t;
  for (int i = 1; i <= n; i++)
    if (a[i] < 0)
      {
        while (!s.empty())
          {
            if (a[s.top()] + a[i] == 0 && t.empty()) break;
            if (!t.empty() && a[s.top()] == a[t.top()])
              {
                a[t.top()] = - a[t.top()];
                s.pop();
                t.pop();
              }
             else
              {
                t.push(s.top());
                s.pop();
              }
          }
          if (!t.empty() || s.empty())
            {
              printf("NO");
              return 0;
            }

        s.pop();

      }
    else s.push(i);

  while (!s.empty() )
    if (!t.empty() && a[s.top()] == a[t.top()])
      {
        a[t.top()] = - a[t.top()];
        s.pop();
        t.pop();
      }
    else
      {
        t.push(s.top());
        s.pop();
      }

  if (!t.empty())
    {
      printf("NO");
      return 0;
    }

  printf("YES\n");
  for (int i = 1; i <= n; i++) printf("%d ", a[i]);
  system("pause");
}


#include <iostream>
#include <cstdio>
using namespace std;
long long n,m,i,j,k,T,q,tot,top,t,x,y,tmp;
long long a[1000005],op[1000005],cnt[1000005],used[1000005];
struct node{
 long long dat,num;
};
node b[1000005],s[1000005];
bool flag;

bool cmp(node x,node y){
 return x.dat<y.dat;
}

int main()
{
  scanf("%I64d",&n);
  if((n&1)==1){ printf("NO\n"); return 0; }
  for(i=1;i<=n;i++){ scanf("%I64d",&a[i]); b[i].dat=a[i]; b[i].num=i; }
  scanf("%I64d",&T);
  for(i=1;i<=T;i++){ scanf("%I64d",&q); a[q]=-a[q]; }

//
  sort(b+1,b+1+n,cmp);  //b[i] from low to high
  tot=0;
  for(i=1;i<=n;i++)
  { if(b[i].dat!=b[i-1].dat)tot++;
    op[b[i].num]=tot;
  }

//
  top=0; t=0;
  for(i=1;i<=n;i++)
  {
    if(a[i]>0){ top++; s[top].dat=a[i]; s[top].num=i; }
    else
    { t++;
      x=abs(a[i]); flag=false;
      while(top>0)
      {
        if(s[top].dat==x)
        { flag=true; top--; break; }
        tmp=op[s[top].num]; y=s[top].num;
        if(used[tmp]!=t){ used[tmp]=t; cnt[tmp]=0; }
        if((cnt[tmp]&1)==0)a[y]=-a[y];
        cnt[tmp]++;
        top--;
      }
      if(!flag){ printf("NO\n"); return 0; }
    }
  }
  t++;
  while(top>0)
  {
    tmp=op[s[top].num]; y=s[top].num;
    if(used[tmp]!=t){ used[tmp]=t; cnt[tmp]=0; }
    if((cnt[tmp]&1)==0)a[y]=-a[y];
    cnt[tmp]++;
    top--;
  }

//
  top=0;
  for(i=1;i<=n;i++)
  {
    if(a[i]>0){ top++; s[top].dat=a[i]; s[top].num=i; }
    else
    { x=abs(a[i]);
      if(s[top].dat!=x){ printf("NO\n"); return 0; }
      top--;
    }
  }

  printf("YES\n");
  for(i=1;i<=n;i++)printf("%I64d ",a[i]);
  printf("\n");

//
  //system("pause");
  return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
#define Order(p) (p.first)
#define Pos(p) (p.second.first)
#define Value(p) (p.second.second)
#define mp make_pair
using namespace std;

typedef pair<int, pair<int, int> > pii;
const int MAX = 1000000 + 2;
bool vis[MAX];
int ans[MAX];
int top = 0;

class Treap
{
	private:
	struct node {
		pii val;
		int key;
		int size;
		node *child[2];

		int rnd() {
			static int KEY = 12345678;
			return KEY += KEY << 2 | 1;
		}

		node(pii _val, node *c) {
			val = _val;
			key = rnd();
			child[0] = child[1] = c;
			size = 1;
		}

		void rz() {
			size = child[0]->size + child[1]->size + 1;
		}
	};

	node *root, *Null;
	void rotate(node *&t, bool d);
	void _insert(node *&t, pii x);
	void _del(node *&t, pii x);
	pii _kth(node *&t, int x);

	public:
	Treap();
	void insert(pii x);
	void del(pii x);
	pii kth(int x);
	int size();
	pii Min();
} T;

void Treap::rotate(node *&t, bool d)
{
	node *p = t->child[d];
	t->child[d] = p->child[!d];
	p->child[!d] = t;
	t->rz();
	p->rz();
	t = p;
}

void Treap::_insert(node *&t, pii x)
{
	if (t == Null) {
		t = new node(x, Null);
	}
	else {
		bool d = x > t->val;
		_insert(t->child[d], x);
		if (t->child[d]->key < t->key) {
			rotate(t, d);
		}
		else {
			t->rz();
		}
	}
}

void Treap::_del(node *&t, pii x)
{
	if (t != Null) {
		if (t->val == x) {
			bool d = t->child[0]->key > t->child[1]->key;
			if (t->child[d] == Null) {
				delete t;
				t = Null;
				return;
			}
			rotate(t, d);
			_del(t->child[!d], x);
		}
		else {
			bool d = x > t->val;
			_del(t->child[d], x);
		}
		t->rz();
	}
}

pii Treap::_kth(node *&t, int x)
{
	int r = t->child[0]->size;
	if (x == r) {
		return t->val;
	}
	else if (x < r) {
		return _kth(t->child[0], x);
	}
	else {
		return _kth(t->child[1], x - r - 1);
	}
}

Treap::Treap()
{
	Null = new node(pii(0, mp(0, 0)), 0);
	Null->size = 0;
	Null->key = INT_MAX;
	Null->child[0] = Null->child[1] = Null;
	root = Null;
}

void Treap::insert(pii x)
{
	_insert(root, x);
}

void Treap::del(pii x)
{
	_del(root, x);
}

pii Treap::kth(int x)
{
	return _kth(root, x);
}

int Treap::size()
{
	return root->size;
}

pii Treap::Min()
{
	node *p = root;
	while (p->child[0] != Null) {
		p = p->child[0];
	}
	return p->val;
}

void run()
{
	memset(vis, 0, sizeof(vis));
	while (T.size()) {
		pii k = T.Min();
		ans[Pos(k)] = Value(k);
		if (~Value(k)) {
			vis[Value(k)] = true;
		}
		T.del(k);
	}
}

void print(int i)
{
	static int p = 1;
	if (~ans[i]) {
		printf("%d", ans[i]);
	}
	else {
		while (vis[p]) {
			p++;
		}
		printf("%d", p++);
	}
}

int main(void)
{
	int n, m, i, x, y;
	cin >> n >> m;
	for (i = 1; i <= n; i++) {
		T.insert(pii(i, mp(i, -1)));
	}

	while (m--) {
		scanf("%d%d", &x, &y);
		pii k = T.kth(y - 1);
		if (Value(k) == -1) {
			if (vis[x]) {	//���ڶ��γ���ĳ��ֵʱ����ֵ��Ӧ��ԭʼλ���Ѿ�ȷ�����������Ҳ�����λ�ã�ì��
				puts("-1");
				return 0;
			}
			else {
				vis[x] = true;
			}
		}
		else if (Value(k) != x) {	//��λ����ȷ��ֵ����Ϊx
			puts("-1");
			return 0;
		}
		//top--��֤�õ���Ϊ��һ��λ�ò���
		//��ȷ��Pos(k)λ��ֵΪx
		T.insert(pii(top--, mp(Pos(k), x)));
		T.del(k);	//ɾ��ԭ���
	}

	run();
	for (i = 1; i < n; i++) {
		print(i);
		putchar(' ');
	}
	print(n);
	putchar('\n');

	return 0;
}


#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <float.h>
#include <cassert>

using namespace std;

#define REP(i, from, to) for (int i = (from); i < (to); ++i)
#define FOR(i, n) REP(i, 0, (n))
#define ALL(x) x.begin(), x.end()
#define SIZE(x) (int)x.size()
#define PB push_back
#define MP make_pair

typedef long long i64;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef vector<VS> VVS;
typedef pair<int, int> PII;

vector<int> t;
int n;

void init (int nn)
{
    n = nn;
    t.assign (n, 0);
}

int sum (int r)
{
    int result = 0;
    for (; r >= 0; r = (r & (r+1)) - 1)
        result += t[r];
    return result;
}

void inc (int i, int delta)
{
    for (; i < n; i = (i | (i+1)))
        t[i] += delta;
}

int sum (int l, int r)
{
    return sum (r) - sum (l-1);
}

void init (vector<int> a)
{
    init ((int) a.size());
    for (unsigned i = 0; i < a.size(); i++)
        inc (i, a[i]);
}

int findIndex(int index) {
    int l = 0, r = n;
    while (l < r) {
        int const m = (l + r) >> 1;
        int const count = sum(m);
        if (count < index)
            l = m + 1;
        else
            r = m;
    }

    return l;
}

void test(int m, VI a) {
    int const n = SIZE(a);
    cout << n << endl;
    while (m--) {
        int const y = rand() % n;
        int const x = a[y];

        cout << x << " " << y + 1 << endl;
        a.erase(a.begin() + y);
        a.insert(a.begin(), x);
    }

    cout << "Will be:\n";
    FOR (i, SIZE(a)) cout << a[i] << " ";
    cout << endl;
}

//#define DEBUG

int main() {
    freopen("input.txt", "r", stdin);

    {
        VI a = {1,2,3};
        //test(5, a);
    }

    ios_base::sync_with_stdio(false);

    int size, m;
    cin >> size >> m;

    int const origSize = size;
    n = 2 * (m + n);
    init(n);
    FOR (i, size) inc(i, 1);

    VI index(size);
    VI state(2 * size + 100);

    VI position(origSize + 10, -1);

    FOR (i, m) {
        int x, y;
        cin >> x >> y;

        int const needIndex = origSize - y + 1;
        int const whereIndex = findIndex(needIndex);

#ifdef DEBUG
        {
            cout << "x = " << x << ", y = " << y << endl;
            cout << "needIndex = " << needIndex << endl;
            cout << "whereIndex = " << whereIndex << endl;
            cout << "position[" << x << "] = " << position[x] << endl;
            cout << "prev position index = " << sum(position[x]) << endl;
        }
#endif

        int const whatThere = state[whereIndex];
        if (whatThere && whatThere != x) {
            //cout << "another number is at the " << whereIndex << " position.\n";
            cout << "-1\n";
            return 0;
        }

        if (position[x] != -1 && sum(position[x]) != needIndex) {
            cout << "-1\n";
            return 0;
        }

        inc(whereIndex, -1);
        state[size] = x;
        inc(size, 1);
        position[x] = size;

#ifdef DEBUG
        cout << "size = " << size << endl;

        cout << "State: ";
        FOR (i, size + 1) {
            cout << sum(i, i) << " ";
        }
        cout << endl;

        cout << "sum(position[x]) = " << sum(position[x]) << endl;
        assert(sum(position[x]) == origSize);
        cout << "new position[" << x << "] = " << position[x] << endl;
#endif
        ++size;

        if (whereIndex < origSize) {
            index[origSize - whereIndex - 1] = x;
#ifdef DEBUG
            cout << "write to " << origSize - whereIndex - 1 << ", x = " << x << endl;
#endif
        }
    }

    set<string> notUsed;
    FOR (i, origSize) {
        ostringstream oss;
        oss << i + 1;
        notUsed.insert(oss.str());
    }
    FOR (i, origSize) if (index[i]) {
        ostringstream oss;
        oss << index[i];
        notUsed.erase(oss.str());
    }

    FOR (i, origSize) {
        if (i) cout << " ";
        if (!index[i]) {
            index[i] = atoi((*notUsed.begin()).c_str());
            notUsed.erase(notUsed.begin());
        }
        cout << index[i];
    }

    cout << endl;

    return 0;
}