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

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for(auto it = d.b;it != d.e;++it)
    *this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

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

  int n, m;cin >> n >> m;
  set<int> s;
  vector<int> cnt(2000000);
  vector<int> arr(n);
  for(int i = 0;i < n;i++)cin >> arr[i];
  for(int i = 0;i <= n;i++)s.insert(i);
  for(int i = 0;i < m;i++){
    s.erase(arr[i]);
    cnt[arr[i]]++;
  }
  int ans = *s.begin();
  for(int i = m;i < n;i++){
    cnt[arr[i - m]]--;
    if(cnt[arr[i - m]] == 0)s.insert(arr[i - m]);
    cnt[arr[i]]++;
    s.erase(arr[i]);
    ans = min(ans, *s.begin());
  }
  cout << ans << endl;
}

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

bool comp(string& a, string& b) {
	return int(a.length()) < int(b.length());
}

bool check(char** ans,string &s, int i, int j, int n,unordered_map<char,vector<int>>& ii) {
	bool flg = true;

	for(int a=0;a<int(s.length());a++) {
		if (ans[(a+i)%n][j]!=s[a] && ans[(a+i)%n][j]!='.') {
			flg = false;
			break;
		}
	}
	if (flg) {
		for(int a=0;a<int(s.length());a++) {
			ans[(a+i)%n][j] = s[a];
			vector<int> t = {(a+i)%n,j};
			ii[s[a]] = t;
		}
		return flg;
	}
	for(int a=0;a<int(s.length());a++) {
		if (ans[(i-a+n)%n][j]!=s[a] && ans[(i-a+n)%n][j]!='.') {
			flg = false;
			break;
		}
	}
	if (flg) {
		for(int a=0;a<int(s.length());a++) {
			ans[(i-a+n)%n][j] = s[a];
			vector<int> t = {(i-a+n)%n,j};
			ii[s[a]] = t;
		}
		return flg;
	}

	for(int a=0;a<int(s.length());a++) {
		if (ans[i][(j+a)%n]!=s[a] &&ans[i][(j+a)%n]!='.') {
			flg = false;
			break;
		}
	}
	if (flg) {
		for(int a=0;a<int(s.length());a++) {
			ans[i][(j+a)%n] = s[a];
			vector<int> t = {i,(j+a)%n};
			ii[s[a]] = t;
		}
		return flg;
	}
	for(int a=0;a<int(s.length());a++) {
		if (ans[i][(j-a+n)%n]!=s[a] &&ans[i][(j-a+n)%n]!='.') {
			flg = false;
			break;
		}
	}
	if (flg) {
		for(int a=0;a<int(s.length());a++) {
			ans[i][(j-a+n)%n] = s[a];
			vector<int> t = {i,(j-a+n)%n};
			ii[s[a]] = t;
		}
	}
	return flg;
}

void solve(char** ans, vector<string>& s, int n) {
	unordered_map<char,vector<int>> ii;
	queue<vector<int>> que;
	for(int i=0;i<n;i++) {
		for(int j=0;j<n;j++) {
			vector<int> t = {i,j};
			que.push(t);
		}
	}

	for(int i=0;i<s.size();i++) {
		string& tar = s[i];
		auto itr = ii.find(tar[0]);

		if (itr!=ii.end()) {
			vector<int> kouho = ii[tar[0]];
			check(ans, tar, kouho[0], kouho[1], n,ii);
		}

		if (que.size()==0) continue;
		auto k = que.front();
		que.pop();
		check(ans, tar, k[0],k[1],n,ii);
	}

}

int main() {
	int n,m;
	cin >> n;
	cin >> m;
	vector<string> s;
	s.reserve(m);
	string t;
	for(int i=0;i<m;i++) {
		cin >> t;
		s.push_back(t);
	}
	sort(s.begin(),s.end(),comp);

	char **ans = new char*[n];
	for(int i=0;i<n;i++) {
		ans[i] = new char[n];
		for(int j=0;j<n;j++) {
			ans[i][j] = '.';
		}
	}
	solve(ans,s,n);
	for(int i=0;i<n;i++) {
		cout << ans[i] << endl;
	}

	return 0;
}


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

int main() {
    ll a, b, c, d;
    cin >> a >> b >> c >> d;
    a = c - a, b = d - b;
    if (a == 0 && b == 0) cout << 0 << endl;
    else if (a + b == 0 || a - b == 0 || abs(a) + abs(b) <= 3) cout << 1 << endl;
    else if ((a + b) % 2 == 0 || abs(abs(a) - abs(b)) <= 6 || abs(a) + abs(b) <= 6) cout << 2 << endl;
    else cout << 3 << endl;
    return 0;
}

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

#define REP(i, n) for(int i = 0; i < n; ++i)
#define GETVEC(v) for(auto& m : v) cin >> m;
using namespace std;
using LLONG = long long;
const LLONG MOD = 1000000007;

int main()
{
	int r1, c1, r2, c2; cin >> r1 >> c1 >> r2 >> c2;
	int ans = -1;
	if (r1 == r2 && c1 == c2)
	{
		ans = 0;
	}
	else if (abs(r1 - r2) + abs(c1 - c2) <= 3 || abs(r1 - r2) == abs(c1 - c2))
	{
		ans = 1;
	}
	else if ((r1 + c1) % 2 == (r2 + c2) % 2)
	{
		ans = 2;
	}
	else
	{
		ans = 3;
		for (int r = r1 - 2; r <= r1 + 2; ++r)
		{
			for (int c = c1 - 2; c <= c1 + 2; ++c)
			{
				if (abs(r - r2) + abs(c - c2) <= 3
					|| abs(r - r2) == abs(c - c2))
				{
					ans = 2;
				}
			}
		}
	}

	cout << ans << endl;
}


#include <bits/stdc++.h>

#define rep(i, n) for (auto i = 0; i < n; ++i)
#define ALL(a) a.begin(), a.end()

using namespace std;

using ll = long long int;

const int MOD_NUM = 1e9 + 7;

struct Item {
    int size;
    int value;
};

bool compare_item_greater(const Item& l, const Item& r) {
    return l.value == r.value ? l.size < r.size : l.value > r.value;
}

int main() {
    // Input
    int N, M, Q;
    cin >> N >> M >> Q;
    vector<int> W(N), V(N), X(M);
    rep(i, N) cin >> W[i] >> V[i];
    rep(i, M) cin >> X[i];

    vector<Item> items(N);
    rep(i, N) items[i] = {W[i], V[i]};
    sort(ALL(items), compare_item_greater);

    for (; Q > 0; Q--) {
        // Input
        int L, R;
        cin >> L >> R;

        // Process
        vector<int> x(L - 1 + M - R);
        copy(X.begin(), X.begin() + L - 1, x.begin());
        copy(X.begin() + R, X.end(), x.begin() + L - 1);
        sort(ALL(x));

        int ans = 0;
        for (Item item : items) {
            auto iter = lower_bound(ALL(x), item.size);
            if (iter != x.end()) {
                ans += item.value;
                x.erase(iter);
            }
        }

        // Output
        cout << ans << endl;
    }

    return 0;
}

#include <bits/stdc++.h>
#include <map>
#include <iostream>

using namespace std;
typedef long long ll;
typedef long double ld;
#define BIG 200005
int N;
struct Data{
    int ind;
    int label; // ans
    bool tree = false; // in tree?
    vector<pair<int, int>> edges; // node, label
    vector<pair<int, int>> tree_edges;

};
vector<Data> nodes(BIG);

bool make_tree(int p, int c){
    if(nodes[c].tree) return false;
    nodes[c].tree = true;
    for(auto child: nodes[c].edges){
        if(child.first == p) continue;
        bool created = make_tree(c, child.first);
        if(created){
            nodes[c].tree_edges.push_back(make_pair(child.first, child.second));
        }
    }
    return true;
}

void solve(int p, int c, int l){
    // decide my label
    if(p!=l){
        nodes[c].label = l;
    }else{
        // l以外の適当な値
        nodes[c].label = l % N + 1;
    }
    for(auto child: nodes[c].tree_edges){
        solve(nodes[c].label, child.first, child.second);
    }
}

int main() {
    int M;
    cin >> N >> M;
    for(int i=0;i<M;i++){
        int u, v, c;
        cin >> u >> v >> c;
        u--;
        v--;
        nodes[u].edges.push_back(make_pair(v, c));
        nodes[v].edges.push_back(make_pair(u, c));
    }
    // make a tree
    make_tree(-1, 0);
    solve(1, 0, 1);
    for(int i=0;i<N;i++){
        Data d = nodes[i];
        printf("%d\n", d.label);
    }
    return 0;
}


#include <iostream>

using namespace std;

const int kMaxN = 20;
const int kMaxL = 73;
const int kP[kMaxN] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71};

int s[kMaxL], c;
long long f[kMaxL + 1][1 << kMaxN], a, b, ans;

long long C(int i, int j) {
  if (f[i][j]) {
    return f[i][j];
  }
  f[i][j] = 1;
  for (int k = i; k <= b - a; k++) {
    if (s[k] && (j & s[k]) == 0) {
      f[i][j] += C(k + 1, j | s[k]);
    }
  }
  return f[i][j];
}

int main() {
  cin >> a >> b;
  for (long long i = a; i <= b; i++) {
    for (int j = 0; j < kMaxN; j++) {
      s[i - a] |= (i % kP[j] == 0) << j;
    }
    c += !s[i - a];
  }
  cout << C(0, 0) * (1 << c);
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_p(x) cerr<<#x": "<<(x).first<<' '<<(x).second<<endl
#define dbg_v(x, n) {cerr<<#x"[]: ";for(long long _=0;_<n;++_)cerr<<(x)[_]<<' ';cerr<<endl;}
#define all(v) v.begin(), v.end()
#define fi first
#define se second
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}

template<typename T1, typename T2>
ostream& operator <<(ostream &out, const pair<T1, T2> &item) {
	out << '(' << item.first << ", " << item.second << ')';
	return out;
}

template <typename T>
ostream& operator <<(ostream &out, const vector<T>& v) {
	for(const auto &item : v) out << item << ' ';
	return out;
}

const int N = 15;

char s[N][N], aux[N][N];

void rot(int &m, int &n) {
	for(int i = 0; i < m; ++i)
		for(int j = 0; j < n; ++j)
			aux[n - 1 - j][i] = s[i][j];

	swap(m, n);
	for(int i = 0; i < m; ++i)
		for(int j = 0; j < n; ++j)
			s[i][j] = aux[i][j];
}

int solve(int m, int n) {
	int last, res = 0;

	for(int j = 1; j < n; ++j) {
		last = -2;
		for(int i = 0; i < m; ++i)
			if(s[i][j] == '#' && s[i][j - 1] == '.') {
				if(i != last + 1) ++res;
				last = i;
			}
	}

	return res;
}

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

	int m, n;

	cin >> m >> n;

	for(int i = 0; i < m; ++i) cin >> s[i];

	int ans = 0;
	for(int i = 0; i < 4; ++i) {
		rot(m, n);
		/*for(int r = 0; r < m; ++r, cerr << '\n')
			for(int c = 0; c < n; ++c) cerr << s[r][c];
		cerr << '\n';*/
		ans += solve(m, n);
	}

	cout << ans << '\n';

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

void fastStd()
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
}

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

	fastStd();

	string s;
	cin >> s;
	int n = s.length();
	vector<int> arr(n);

	for(int i = 0; i < n; i++){
		arr[i] = (s[i] - '0') % 3;
	}

	vector<vector<int>> dp(n, vector<int>(3, 0));
	// dp[0][arr[0]] = 1;
	for(int i = 0; i < n; i++){
		dp[i][arr[i]] = 1;
	}
	for(int i = 1; i < n; i++){
		for(int j = 0; j < 3; j++){
			// int a = dp[i][(j+arr[i])%3] + dp[i-1][j];
			if(dp[i-1][j] != 0)
				dp[i][(j+arr[i])%3] = max(dp[i-1][j] + 1, dp[i-1][(j+arr[i])%3]);
			else
				dp[i][(j+arr[i])%3] = max(dp[i-1][(j+arr[i])%3], dp[i][(j+arr[i])%3]);
		}
		// for(int j = 0; j < 3; j++){
		// 	printf("%d ", dp[i][j]);
		// }
		// printf("\n");
	}
	if(dp[n-1][0] != 0){
		cout << n - dp[n-1][0] << "\n";
	} else {
		cout << -1 << "\n";
	}

	return 0;
}

#include<bits/stdc++.h>

using namespace std;

#define MOD 1000000007
#define deb(x) cout << #x << " = " << x << endl
#define deb2(x,y) cout << #x << " = " << x << ", " << #y << " = " << y << endl
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626

typedef long long ll;

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

    string s;
    cin>>s;
    int n = s.length();
    int ar[n];

    int sum = 0;

    for(int i=0; i<n; i++)ar[i] = ((s[i]-'0')%3);
    for(int i=0; i<n; i++)sum+=ar[i];

    if(sum%3==0)
    {
        cout<<"0";
        return 0;
    }

    int yo = sum%3;
    int c[3];
    c[0] = 0; c[1] = 0; c[2] = 0;

    for(int i=0; i<n; i++)
    {
        c[ar[i]]++;
    }

    if(yo==1)
    {
        if(c[1]>0)
        {
            if(n>1)cout<<"1";
            else cout<<"-1";
        }
        else if(c[2]>1)
        {
            if(n>2)cout<<"2";
            else cout<<"-1";
        }
        else cout<<"-1";
    }
    else
    {
        if(c[2]>0)
        {
            if(n>1)cout<<"1";
            else cout<<"-1";
        }
        else if(c[1]>1)
        {
            if(n>2)cout<<"2";
            else cout<<"-1";
        }
        else cout<<"-1";
    }

    return 0;
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using vec = vector<ll>;
using mat = vector<vec>;
using pll = pair<ll,ll>;

#define INF (1LL << 60)
#define MOD 1000000007
#define PI 3.14159265358979323846

#define REP(i,m,n) for(ll (i)=(m),(i_len)=(n);(i)<(i_len);++(i))
#define FORR(i,v) for(auto (i):v)
#define ALL(x) (x).begin(), (x).end()
#define PR(x) cout << (x) << endl
#define PS(x) cout << (x) << " "
#define SZ(x) ((ll)(x).size())
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define REV(x) reverse(ALL((x)))
#define ASC(x) sort(ALL((x)))
#define DESC(x) ASC((x)); REV((x))
#define pb push_back
#define eb emplace_back

bool check(mat A, ll X, ll N, ll K)
{
    mat S(N+1, vec(N+1, 0));
    bool f = false;
    REP(i,1,N+1) {
        REP(j,1,N+1) {
            S[i][j] = S[i-1][j] + S[i][j-1] - S[i-1][j-1] + (A[i-1][j-1] > X);
        }
    }
    REP(i,1,N-K+2) {
        REP(j,1,N-K+2) {
            ll cnt = S[i+K-1][j+K-1] - S[i+K-1][j-1] - S[i-1][j+K-1] + S[i-1][j-1];
            if(cnt < K*K/2+1) {
                f = true;
                break;
            }
        }
    }
    return f;
}

int main()
{
    ll N, K;
    cin >> N >> K;
    mat A(N, vec(N));
    REP(i,0,N) {
        REP(j,0,N) cin >> A[i][j];
    }

    ll ng = -1, ok = INF;
    while(abs(ok - ng) > 1) {
        ll mid = (ok + ng) / 2;
        if(check(A, mid, N, K)) ok = mid;
        else ng = mid;
    }
    PR(ok);

    return 0;
}

/*

*/

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 5000 + 10;
const LL MOD = 998244353;
int n, m;
LL mpow(LL a, LL x) {
	if (x == 0) return 1;
	LL t = mpow(a, x>>1);
	if (x % 2 == 0) return t * t % MOD;
	return t * t % MOD * a % MOD;
}

LL f[N][N], pw[N][N];

int main() {
	pw[0][0] = 1;
	for (int i = 1; i < N; i ++) {
		pw[i][0] = 1;
		for (int j = 1; j < N; j ++) pw[i][j] = pw[i][j-1] * i % MOD;
	}
	cin >> n >> m;
	for (int i = 1; i <= m; i ++) {
		f[1][i] = pw[m][n-1];
	}
	for (int i = 2; i <= n; i ++) {
		for (int x = 1; x <= m; x ++) {
			f[i][x] = f[i-1][x] - pw[m-x][i-2] * pw[m][n-(i-1)] % MOD +
				pw[m-x][i-1] * pw[m][n-i] % MOD +
				pw[m-x][i-2] * (x-1) % MOD * pw[m][n-i] % MOD;

			f[i][x] = (f[i][x] % MOD + MOD) % MOD;
			//printf("# %d %d : %d\n", i, x, f[i][x]);
		}
	}
	LL ans = 0;
	for (int i = 1; i <= n; i ++) for (int x = 1; x <= m; x ++) (ans += f[i][x]) %= MOD;
	cout << ans << endl;
}


#include <bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define debugg(x) cout<<#x<<'='<<x<<endl;
#define debug1(x,y,z) cout<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<endl;
#define debug cout<<endl<<"********"<<endl;
#define ll long long
#define ull unsigned long long
#define ding cerr<<endl<<"Time: "<<(clock() * 1000. / CLOCKS_PER_SEC)<<" ms"<<endl;
#define ld long double
#define itn int
#define pi (int)(3.1415926536)
#define pii pair<int,int>
#define rep(I, A, B) for (int I = (A); I <= (B); ++I)
#define dwn(I, A, B) for (int I = (A); I >= (B); --I)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define mod (ll)(1e9+7)
#define mod1 (ll)(1e9)
#define int ll
void fre(){
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
}
void fc(){fclose(stdin);fclose(stdout);}
inline ll ccin(){
    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*10+ch-'0',ch=getchar();
    return x*f;
}
inline void cou(ll x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) cou(x/10);
    putchar(x%10+'0');
}

const int maxn=2e5+10;
const ll inf=1e16;
const int maxm=5e5+10;

int n;
struct node{
    int v;int w;
};
vector<node> yuan[maxn];
int zhi[maxn],cnt0[70],cnt1[70];
void dfs(int now,int fa,int val){
    zhi[now]=val;
    for(int i=0;i<yuan[now].size();i++){
        int v=yuan[now][i].v;
        if(v==fa) continue;
        dfs(v,now,val^yuan[now][i].w);
    }
}

signed main(){
    ios;
    cin>>n;
    for(int i=1;i<n;i++){
        int a1,a2,a3;cin>>a1>>a2>>a3;
        yuan[a1].push_back((node){a2,a3});
        yuan[a2].push_back((node){a1,a3});
    }
    dfs(1,0,0);
    for(int i=0;i<=61;i++){
        int now=(1LL<<i);
        for(int j=1;j<=n;j++){
            if(now&zhi[j]) cnt1[i]++;
            else cnt0[i]++;
        }
    }
    ll ans=0;
    for(int i=0;i<=61;i++){
        ll now=(1LL<<i)%mod;
        ll cnt=cnt1[i]*cnt0[i]%mod;
        ans=(ans+now*cnt)%mod;
    }
    cout<<ans<<endl;
    ding;return 0;
}

#include <bits/stdc++.h>
#define Rep(i,n,m) for(int i=(int)(n);i<(int)(m);i++)
#define rep(i,n) Rep(i,0,n)
#define all(v) v.begin(),v.end()
using namespace std;
using ll=long long;
using vi=vector<int>;
using vll=vector<ll>;
#define _GLIBCXX_DEBUG
vll g;
using pii=pair<int,ll>;
using graph=vector<vector<pii>>;
const ll mod=1000000007;

void dfs(graph &G,int v,int p,ll m){
  g[v]=m;
  for(auto q:G[v]){
    if(q.first==p) continue;
    dfs(G,q.first,v,m^q.second);
  }
}
int main(){
  int N;cin>>N;
  vll pw(60);pw[0]=1;
  rep(i,59) pw[i+1]=pw[i]*2;
  graph G(N);
  rep(i,N-1){
    int x,y;ll z;cin>>x>>y>>z;x--;y--;
    G[x].push_back({y,z});G[y].push_back({x,z});
  }
  g=vll(N);
  dfs(G,0,-1,0);
  vll cn(60);
  rep(i,N){
    rep(j,60){
      if(g[i]&pw[j]) cn[j]++;
    }
  }
  ll ans=0;

  rep(i,60){
    ans+=pw[i]%mod*cn[i]%mod*(N-cn[i])%mod;
    ans%=mod;
  }
  cout << ans << endl;
  return 0;
}


#include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
#define DBG(a) cout<< "line "<<__LINE__ <<" : "<< #a <<" --> "<<(a)<<endl
#define eps 1e-8
#define eq(x,y) (fabs((x)-(y)) < eps)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int>pii;
const int mod = 998244353;
long double pi = acosl(-1);
const ll infl = 1e17+100;
const int inf = 1e9+100;
const int nmax = 1e6+5;
const int MAXLG = log2(nmax)+1;
//mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
//typedef tree< ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ost;

multiset<int>nibo;
vector<int>v1, v2;

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

    int n;
    cin>>n;
    v1.resize(n), v2.resize(n);
    for(int &x : v1) cin>>x;
    for(int &x : v2) cin>>x;
    reverse(v2.begin(), v2.end());

    ll ans = 0;
    for(int i=0; i<n; i++){
        int x1 = v1.back(), x2 = v2.back();
        v1.pop_back(), v2.pop_back();
        if(x1>x2) swap(x1,x2);
        if(i==0){
            nibo.insert(x2);
        }
        else{
            auto it = nibo.begin();
            if( *it < x1){
                nibo.erase(it);
                nibo.insert(x2);
                nibo.insert(x1);
            }
            else {
                nibo.insert(x2);
            }
        }
//        for(int x : nibo) cout<<x<<" ";
//        cout<<"aa "<<endl;
    }
    for(int x : nibo) ans += x;
    cout<<ans<<endl;
}
/*
*/

#include <bits/stdc++.h>

using namespace std;
#define int long long
const int MOD = 1000000007;
template <class T>
struct fenwick_tree {
	vector<T> x;
	fenwick_tree(int n) : x(n, 0) {}
	T sum(int i, int j) {
		if (i == 0) {
			T S = 0;
			for (j; j >= 0; j = (j & (j + 1)) - 1) S += x[j];
			return S;
		} else
			return sum(0, j) - sum(0, i - 1);
	}
	void add(int k, T a) {
		for (; k < x.size(); k |= k + 1) x[k] += a;
	}
};
signed main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int N;
	cin >> N;
	vector<int> A(2 * N);
	int res = 0;
	for (int i = 0; i < 2 * N; i++) {
		cin >> A[i];
	}
	vector<int> B;
	for (int i = 0; i < N; i++) {
		B.push_back(min(A[N - 1 - i], A[i + N]));
		B.push_back(max(A[N - 1 - i], A[i + N]));
	}

	int sum = 0;
	priority_queue<int> pq;
	for (int i = 1; i < 2 * N; i++) {
		if (i % 2 == 0) {
			int a = -pq.top();
			if (a < B[i]) {
				res += B[i] - a;
				pq.pop();
				pq.push(-B[i]);
			}
		} else {
			res += B[i];
			pq.push(-B[i]);
		}
	}
	// fenwick_tree<int> ft(2 * N);
	// for (int i = 0; i < 3 * N; i++) {
	// 	ft.add(i, 1);
	// }
	// vector<pair<int, int> > vp;
	// for (int i = 0; i < 2 * N; i++) {
	// 	vp.emplace_back(B[i], i);
	// }
	// sort(B.rbegin(), B.rend());
	// for (int i = 0; i < 2 * N; i++) {
	// 	//cerr << vp[i].first << " " << vp[i].second << endl;
	// 	int p = vp[i].second;
	// 	if (ft.sum(0, p) - 2 >= 0) {
	// 		ft.add(p, -2);
	// 		res += vp[i].first;
	// 	}
	// }
	cout << res << endl;
}


/*
    author:  Maksim1744
    created: 20.02.2021 15:01:36
*/

#include "bits/stdc++.h"

using namespace std;

#define ll   long long
#define ld   long double

#define mp   make_pair
#define pb   push_back
#define eb   emplace_back

#define sum(a)     ( accumulate ((a).begin(), (a).end(), 0ll))
#define mine(a)    (*min_element((a).begin(), (a).end()))
#define maxe(a)    (*max_element((a).begin(), (a).end()))
#define mini(a)    ( min_element((a).begin(), (a).end()) - (a).begin())
#define maxi(a)    ( max_element((a).begin(), (a).end()) - (a).begin())
#define lowb(a, x) ( lower_bound((a).begin(), (a).end(), (x)) - (a).begin())
#define uppb(a, x) ( upper_bound((a).begin(), (a).end(), (x)) - (a).begin())

template<typename T>             vector<T>& operator--            (vector<T>& v){for (auto& i : v) --i;            return  v;}
template<typename T>             vector<T>& operator++            (vector<T>& v){for (auto& i : v) ++i;            return  v;}
template<typename T>             istream& operator>>(istream& is,  vector<T>& v){for (auto& i : v) is >> i;        return is;}
template<typename T>             ostream& operator<<(ostream& os,  vector<T>& v){for (auto& i : v) os << i << ' '; return os;}
template<typename T, typename U> pair<T,U>& operator--           (pair<T, U> &p){--p.first; --p.second;            return  p;}
template<typename T, typename U> pair<T,U>& operator++           (pair<T, U> &p){++p.first; ++p.second;            return  p;}
template<typename T, typename U> istream& operator>>(istream& is, pair<T, U>& p){is >> p.first >> p.second;        return is;}
template<typename T, typename U> ostream& operator<<(ostream& os, pair<T, U>& p){os << p.first << ' ' << p.second; return os;}
template<typename T, typename U> pair<T,U> operator-(pair<T,U> a, pair<T,U> b){return mp(a.first-b.first, a.second-b.second);}
template<typename T, typename U> pair<T,U> operator+(pair<T,U> a, pair<T,U> b){return mp(a.first+b.first, a.second+b.second);}
template<typename T, typename U> void umin(T& a, U b){if (a > b) a = b;}
template<typename T, typename U> void umax(T& a, U b){if (a < b) a = b;}

#ifdef HOME
#define SHOW_COLORS
#include "C:/C++ libs/print.cpp"
#else
#define show(...)     42
#define mclock        42
#define shows         42
#define debug if (false)
#endif

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

    auto is_up = [&](char c) {
        return c >= 'A' && c <= 'Z';
    };
    string s;
    cin >> s;
    for (int i = 0; i < s.size(); ++i) {
        if (is_up(s[i]) != i % 2) {
            cout << "No\n";
            return 0;
        }
    }
    cout << "Yes\n";

    return 0;
}

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

int main(){
  string S;cin>>S;
  int l=S.size();
  for(int i=0;i<l;i++){
    if(i%2==0 && S[i]<='Z'){
      cout<<"No"<<endl;
      return 0;
    }
    else if(i%2==1 && S[i]>='a'){
      cout<<"No"<<endl;
      return 0;
    }
  }
  cout<<"Yes"<<endl;
}


//I'll always miss you like a darling.
#include <bits/stdc++.h>
using namespace std;

#define LL long long
#define LD long double
#define ull unsigned long long
#define x first
#define y second
#define pb push_back
#define pf push_front
#define mp make_pair
#define Pair pair<int,int>
#define pLL pair<LL,LL>
#define pii pair<double,double>
#define LOWBIT(x) x & (-x)

#define rep(i,a,b) for (int i=a;i<=b;i++)
#define REP(i,a,b) for (int i=a;i>=b;i--)

const int INF=2e9;
const LL LINF=2e16;
const int magic=348;
const int MOD=1e9+7;
const double eps=1e-10;
const double pi=acos(-1);

struct fastio
{
    static const int S=1e7;
    char rbuf[S+48],wbuf[S+48];int rpos,wpos,len;
    fastio() {rpos=len=wpos=0;}
    inline char Getchar()
    {
        if (rpos==len) rpos=0,len=fread(rbuf,1,S,stdin);
        if (!len) return EOF;
        return rbuf[rpos++];
    }
    template <class T> inline void Get(T &x)
    {
        char ch;bool f;T res;
        while (!isdigit(ch=Getchar()) && ch!='-') {}
        if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
        while (isdigit(ch=Getchar())) res=res*10+ch-'0';
        x=(f?res:-res);
    }
    inline void getstring(char *s)
    {
        char ch;
        while ((ch=Getchar())<=32) {}
        for (;ch>32;ch=Getchar()) *s++=ch;
        *s='\0';
    }
    inline void flush() {fwrite(wbuf,1,wpos,stdout);fflush(stdout);wpos=0;}
    inline void Writechar(char ch)
    {
        if (wpos==S) flush();
        wbuf[wpos++]=ch;
    }
    template <class T> inline void Print(T x,char ch)
    {
        char s[20];int pt=0;
        if (x==0) s[++pt]='0';
        else
        {
            if (x<0) Writechar('-'),x=-x;
            while (x) s[++pt]='0'+x%10,x/=10;
        }
        while (pt) Writechar(s[pt--]);
        Writechar(ch);
    }
    inline void printstring(char *s)
    {
        int pt=1;
        while (s[pt]!='\0') Writechar(s[pt++]);
    }
}io;

template<typename T> inline void check_max(T &x,T cmp) {x=max(x,cmp);}
template<typename T> inline void check_min(T &x,T cmp) {x=min(x,cmp);}
template<typename T> inline T myabs(T x) {return x>=0?x:-x;}
template<typename T> inline T mygcd(T x,T y) {return y==0?x:mygcd(y,x%y);}
inline int add(int x) {if (x>=MOD) x-=MOD;return x;}
inline int add(int x,int MO) {if (x>=MO) x-=MO;return x;}
inline int sub(int x) {if (x<0) x+=MOD;return x;}
inline int sub(int x,int MO) {if (x<0) x+=MO;return x;}
inline void Add(int &x,int y) {x=add(x+y);}
inline void Add(int &x,int y,int MO) {x=add(x+y,MO);}
inline void Sub(int &x,int y) {x=sub(x-y);}
inline void Sub(int &x,int y,int MO) {x=sub(x-y,MO);}
template<typename T> inline int quick_pow(int x,T y) {int res=1;while (y) {if (y&1) res=1ll*res*x%MOD;x=1ll*x*x%MOD;y>>=1;}return res;}
template<typename T> inline int quick_pow(int x,T y,int MO) {int res=1;while (y) {if (y&1) res=1ll*res*x%MO;x=1ll*x*x%MO;y>>=1;}return res;}

const int MAXN=3e5;

int n;
int a[MAXN+48];

namespace BIT
{
    int c[MAXN+48];
    void clear() {memset(c,0,sizeof(c));}
    void modify(int x) {while (x<=n) c[x]++,x+=LOWBIT(x);}
    int query(int x) {int res=0;while (x) res+=c[x],x^=LOWBIT(x);return res;}
}

int main ()
{
#ifndef ONLINE_JUDGE
    double TIME=clock();
    freopen ("a.in","r",stdin);
    freopen ("a.out","w",stdout);
    cerr<<"Running..."<<endl;
#endif
    scanf("%d",&n);rep(i,1,n) scanf("%d",a+i),a[i]++;LL ans=0;
    BIT::clear();rep(i,1,n) ans+=(i-1)-BIT::query(a[i]),BIT::modify(a[i]);
    printf("%lld\n",ans);
    rep(i,1,n-1)
    {
        ans-=(a[i]-1);
        ans+=(n-a[i]);
        printf("%lld\n",ans);
    }
#ifndef ONLINE_JUDGE
    cerr<<"Exec Time: "<<(clock()-TIME)/CLOCKS_PER_SEC<<endl;
#endif
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i, n) for(ll i = 0; i < (ll)(n); ++i)
#define FOR(i, a, b) for(ll i=(a); i < (ll)(b); ++i)
template<class T> inline bool chmax(T& a, T b) { if(a < b){ a=b; return 1; } return 0;}
template<class T> inline bool chmin(T& a, T b) { if(a > b){ a=b; return 1; } return 0;}

const ll MOD = 998244353;

ll calc_pow(ll x, ll n){
	ll ret = 1;
	while(n>0){
		if(n & 1) ret = ret*x%MOD;
		x = x*x%MOD;
		n >>= 1;
	}
	return ret;
}

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

	ll ans=0;

	if(n==1 || m==1){
		ans = calc_pow(k, n*m);

		cout << ans << endl;

		return 0;
	}

	FOR(a,1,k+1){
		ll tmp;
		tmp = ((calc_pow(a, n) - calc_pow(a-1, n))%MOD + MOD)%MOD;

		tmp = (tmp*calc_pow(k+1 - a, m))%MOD;

		ans = (ans+tmp)%MOD;
	}

	cout << ans << endl;

	return 0;
}


#pragma GCC optimize("Ofast")
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cctype>
#include <sstream>
#include <stack>
#include <deque>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <unordered_map>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using Po = pair<double, double>;
template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;

#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=ll(a);i<=ll(b);i++)
#define FORD(i,a,b) for(ll i=ll(a);i>=ll(b);i--)
#define PB push_back
#define MP make_pair
#define SZ(x) ll(x.size())
#define ALL(x) x.begin(),x.end()
#define NIL -1
#define INF pow(2,31)-1
#define MOD 998244353
#define PI 3.14159265358979323846
#define endl "\n"
#define EPS 1e-9

template <class T, class U>

void chmin(T& t, const U& u) {
	if (t > u) t = u;
}
template <class T, class U>

void chmax(T& t, const U& u) {
	if (t < u) t = u;
}

ll powmod(ll x, ll n, ll mod) {
	ll s = 1;
	REP(i, n) {
		s = s * x % mod;
	}
	if (s < 0)s += mod;
	return s;
}

ll gcd(int p, int q) {
	while (q != 0) {
		ll r = p % q;
		p = q;
		q = r;
	}
	return p;
}

V<ll> v(200001);
signed main() {
	ll a, b, c, d;
	cin >> a >> b >> c >> d;
	cout << a * d - b * c << endl;
}

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

#define ll long long
#define ar array
#define sz(v) (int)(v).size()
#define fi first
#define se second
#define pb push_back
#define rep(i,a,b) for(int i = (a) ; i<(b) ; ++i)

const int mxN = 2e5;
const ll MOD = 998244353;

map<char,int> mp;
int n;
vector<ll> c[3];

ll findmin(int a, int b) {
	ll ans = 1e18;
	rep(i,0,sz(c[a])) {
		int pos = lower_bound(c[b].begin(),c[b].end(),c[a][i]) - c[b].begin();
		if(pos<sz(c[b])) {
			ans = min(ans,llabs(c[a][i]-c[b][pos]));
		}
		if(pos-1>=0) {
			ans = min(ans,llabs(c[a][i]-c[b][pos-1]));
		}
	}
	return ans;
}

int main() {
	mp['R'] = 0;
	mp['G'] = 1;
	mp['B'] = 2;
	cin>>n;
	rep(i,0,2*n) {
		char cl;
		ll x;cin>>x>>cl;
		c[mp[cl]].pb(x);
	}
	sort(c[0].begin(),c[0].end());
	sort(c[1].begin(),c[1].end());
	sort(c[2].begin(),c[2].end());
	if(!(sz(c[0])&1) && !(sz(c[1])&1) && !(sz(c[2])&1)) return cout << 0 << "\n",0;
	if(!(sz(c[0])&1)) swap(c[0],c[2]);
	if(!(sz(c[1])&1)) swap(c[1],c[2]);
	cout << min(findmin(0,1),findmin(0,2) + findmin(1,2)) << "\n";

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double ld;

#define int ll
const int N = 50 + 7;
int n;
int y;
int a[N];
int b[N];
int valuey[N];
int dp[N][2];

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

  cin >> n >> y;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  a[n + 1] = (int) 3e18 / a[n] * a[n];
  for (int i = 1; i <= n; i++) {
    b[i] = a[i + 1] / a[i];
  }
  for (int i = n; i >= 1; i--) {
    valuey[i] = y / a[i];
    y %= a[i];
  }
  dp[0][0] = 1;
  for (int i = 1; i <= n; i++) {
    for (int j = 0; j <= 1; j++) {
      dp[i][valuey[i] + j >= b[i]] += dp[i - 1][j];
      int value = dp[i - 1][j];
      int x = b[i] - j - valuey[i];
      if (1 <= x && x < b[i]) {
        dp[i][(x + j + valuey[i]) >= b[i]] += value;
      }
    }
  }
  cout << dp[n][0] << "\n";
}

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

typedef long long lli;
int MOD = 998244353;
inline int add(const int a, const int b, const int mod = MOD) { return (a + b >= mod) ? (a + b - mod) : (a + b); }
inline void _add(int &a, const int b, const int mod = MOD) { a = add(a, b, mod); }
inline int sub(const int a, const int b, const int mod = MOD) { return (a - b < 0) ? (a - b + mod) : (a - b); }
inline void _sub(int &a, const int b, const int mod = MOD) { a = sub(a, b, mod); }
inline int negate(const int a, const int mod = MOD) { return mod - a; }
inline int mul(const int a, const int b, const int mod = MOD) { return (a * 1ll * b) % mod; }
inline void _mul(int &a, const int b, const int mod = MOD) { a = mul(a, b, mod); }
int binPow(int b, lli p, const int mod = MOD) {
	int r = 1;
	while (p) {
		if (p & 1) r = mul(r, b, mod);
		b = mul(b, b, mod);
		p >>= 1;
	}
	return r;
}
int gcdex(int a, int b, int &x, int &y) {
	if (!b) return x = 1, y = 0, a;
	int px, py, res = gcdex(b, a % b, px, py);
	return x = py, y = px - a / b * py, res;
}
int inv(const int a, const int mod = MOD) { // a and mod must be coprime
	int x, y;
	int g = gcdex(a, mod, x, y);
	assert(g == 1);
	x = (x % mod + mod) % mod;
	return x;
}
inline int dvd(const int a, const int b, const int mod = MOD) { // b and mod must be coprime
	int rev = inv(b, mod);
	return mul(a, inv(b, mod), mod);
} // b != 0
inline void _dvd(int &a, const int b, const int mod = MOD) { a = dvd(a, b, mod); } // b and mod must be coprime
inline int convert(int x, const int mod = MOD) {
	int tx = x % mod + mod;
	return tx >= mod ? tx - mod : tx;
};

const int MB = 13;
const int MX = 5005;
vector<int> f, rf;
vector<vector<int>> dp;
int n, m;
int C(int n, int k) {
    if (k < 0 || k > n) return 0;
    return mul(f[n], mul(rf[k], rf[n - k]));
}

int getDp(int sum, int bit) {
    if (sum == 0) return 1;
    if (bit == -1) return 0;
    if (dp[sum][bit] != -1) return dp[sum][bit];

    int one = 1 << bit;
    dp[sum][bit] = 0;
    for (int take = 0; 1ll * take * one <= sum && take <= n; take += 2) {
        _add(dp[sum][bit], mul(C(n, take), getDp(sum - take * one, bit - 1)));
    }
    return dp[sum][bit];
}

int main () {
    f.assign(MX, 0);
    rf.assign(MX, 0);
    f[0] = 1;
    for (int i = 1; i < MX; i++) f[i] = mul(f[i - 1], i);
    rf[MX - 1] = 996779413;
    for (int i = MX - 2; i >= 0; i--) rf[i] = mul(rf[i + 1], i + 1);

    while (scanf("%d %d", &n, &m) == 2) {
        dp.assign(m + 1, vector<int>(MB + 1, -1));
        int res = getDp(m, MB);
        printf("%d\n", res);
    }
}


// author : redwackyferret
#include<bits/stdc++.h>
#define pb push_back
#define pdd pair<ld, ld>
#define int long long
#define ff first
#define pii pair<int,int>
#define ss second
#define pp make_pair
#define endl "\n"
#define ll long long
#define ld long double
#define REP(i,n) for((i)=0;(i)<(int)(n);(i)++)
#define PI 3.1415926535
#define mst(v, x) memset(v, x, sizeof v);
#define all(v) v.begin(), v.end()

// __builtin_clz(x) returns num of zeroes at beginning of bit representation
// __builtin_ctz(x) num of zeroes at end of bit representation
// __builtin_popcount(x) num of ones
// __bultin_parity(x) parity of num of ones in bit representation

using namespace std;

void IOS(){ios::sync_with_stdio(false); cout.precision(10); cout << fixed;}
const int MOD = 1e9 + 7;
#define INF 2000000000
const int mx = 1e5+5;

int i, j, k;

ll gcd(ll x, ll y)
{      if (y == 0)return x;
       return gcd(y, x % y);
}

ll lcm(ll x, ll y){
       return (x*y)/gcd(x,y);
}

struct st{
	int a, b, c;
};

int32_t main(){
	IOS();
	int n,C;
	cin>>n>>C;
	vector<pair<int,int>>event;
	REP(i,n){
		int a,b,c;
		cin>>a>>b>>c;
		event.emplace_back(a-1,c);
		event.emplace_back(b,-c);
	}

	int ans = 0;
	sort(all(event));
	int fee = 0, t=0;
	for(auto z : event){
		int x = z.ff, y = z.ss;
		if(x!=t){
			ans += min(C, fee)*(x-t);
			t=x;
		}
		fee+=y;
	}
	cout<<ans<<endl;

return 0;
}

#include <bits/stdc++.h>

#ifndef M_PI
#define M_PI 3.14159265358979
#endif
#define deg_to_rad(deg) (((deg) / 360) * 2 * M_PI)
#define rad_to_deg(rad) (((rad) / 2 / M_PI) * 360)

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef pair<ll, ll> pll;
typedef pair<int, int> pi;
typedef long double ld;
typedef pair<long double, long double> pld;

const ll INF = 1e18;
const ll MOD = 1e9 + 7;

// べき乗の剰余（a^b mod MOD）
ll bpow(ll a, ll b) {
    ll res = 1;
    while(b) {
        if(b & 1)
            res = 1LL * res * a % MOD;
        a = 1LL * a * a % MOD;
        b >>= 1;
    }
    return res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll i, j;

    ll N, C;
    cin >> N >> C;
    vll va, vb, vc;
    for(i = 0; i < N; i++) {
        ll a, b, c;
        cin >> a >> b >> c;
        va.push_back(a);
        vb.push_back(b);
        vc.push_back(c);
    }
    vector<pll> P;
    for(i = 0; i < N; i++) {
        P.push_back(pll(va[i], vc[i]));
        P.push_back(pll(vb[i] + 1, -1 * vc[i]));
    }
    sort(P.begin(), P.end());

    ll ans = 0;
    ll tc = 0;
    ll now = P[0].first;
    ll pi = 0;
    while(1) {
        while(P[pi].first == now) {
            tc += P[pi].second;
            pi++;
            if(pi >= 2 * N)
                break;
        }
        if(pi >= 2 * N)
            break;
        ll ttc;
        if(tc > C) {
            ttc = C;
        } else {
            ttc = tc;
        }
        ans += ttc * (P[pi].first - now);
        now = P[pi].first;
    }
    cout << ans << endl;

    return 0;
}


#include <bits/stdc++.h>

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

using namespace std;

class union_find{
	int n;
	vector<int> p;
	vector<map<int,int>> f; // color -> number of vertices
public:
	union_find(int n,vector<int> color):n(n),p(n,-1),f(n){
		rep(u,n) f[u][color[u]]=1;
	}
	int find(int u){ return p[u]<0?u:p[u]=find(p[u]); }
	void unite(int u,int v){
		u=find(u); v=find(v);
		if(u!=v){
			if(p[v]<p[u]) swap(u,v);
			p[u]+=p[v]; p[v]=u; n--;
			for(auto [c,k]:f[v]) f[u][c]+=k;
			f[v].clear();
		}
	}
	bool is_same(int u,int v){ return find(u)==find(v); }
	int size()const{ return n; }
	int size(int u){ return -p[find(u)]; }
	int query(int u,int color){
		return f[find(u)][color];
	}
};

int main(){
	int n,q; scanf("%d%d",&n,&q);
	vector<int> color(n);
	rep(u,n) scanf("%d",&color[u]), color[u]--;

	union_find U(n,color);
	rep(_,q){
		int type,a,b; scanf("%d%d%d",&type,&a,&b); a--; b--;
		if(type==1) U.unite(a,b);
		else        printf("%d\n",U.query(a,b));
	}

	return 0;
}

#include <stdio.h>
#include <set>
#include <vector>
#include <utility>
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pl;

int main(void) {
  ll i, j, k, n, m, a, b, c, ans;
  scanf("%lld%lld", &n, &m);
  vector<pl> vec[n];
  for(i = 0; i < m; ++i) {
    scanf("%lld%lld%lld", &a, &b, &c);
    vec[--a].push_back(mp(--b, c));
  }
  ll d[n], t;
  pl p;
  for(i = 0; i < n; ++i) {
    ans = 1e9;
    set<pl> s;
    for(j = 0; j < n; ++j) d[j] = 1e9;
    d[i] = 0;
    for(j = 0; j < n; ++j) s.insert(mp(d[j], j));
    while(s.size()) {
      p = *s.begin(), s.erase(s.begin()), t = p.second;
      for(j = 0; j < vec[t].size(); ++j) {
        if(vec[t][j].first == i && ans > d[t] + vec[t][j].second) ans = d[t] + vec[t][j].second;
        else if(d[vec[t][j].first] > d[t] + vec[t][j].second) {
          s.erase(mp(d[vec[t][j].first], vec[t][j].first));
          d[vec[t][j].first] = d[t] + vec[t][j].second;
          s.insert(mp(d[vec[t][j].first], vec[t][j].first));
        }
      }
    }
    printf("%lld\n", ans == 1e9 ? -1 : ans);
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;
using ull = unsigned long long;
#define rep(i, n) for(long long i = 0; i < n; i++)
#define rep1(i, n) for(long long i = 1; i <= n; i++)
#define rrep(i, n) for(long long i = n; i > 0; i—)
#define rrep1(i, n) for(long long i = n; i >= 0; i—)
//char型　10進数で48が'0'

int main() {
  ll n,sum=0,total=0,ans=0;
  cin >> n;
  vector<ll> v(n);
  rep(i, n){
    ll a,b;
    cin >> a >> b;
    v[i] = a*2 + b;
    total += a;
  }
  sort(v.begin(),v.end());
  for(long long i = n - 1; sum <= total; i--){
    sum += v[i];
    ans += 1;
  }
  cout << ans << endl;
  return 0;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author Kein Yukiyoshi
 */

#include "bits/stdc++.h"
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define REP(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define FOR(i, a) for (auto &i : a)
#define ALL(obj) begin(obj), end(obj)
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define SUM(x) accumulate(ALL(x), 0LL)
#define LOWER_BOUND(A, key) distance(A.begin(), lower_bound(ALL(A), key))
#define UPPER_BOUND(A, key) distance(A.begin(), upper_bound(ALL(A), key))

using namespace std;
const int MOD   = (int)(1e9 + 7);
const int INF   = (int)(1e13 + 7);
const double EPS = 1e-14;
const double PI = acos(-1);

int CEIL(int a, int b) { return (a >= 0 ? (a + (b - 1)) / b : (a - (b - 1)) / b); } //ceil() for int
int mod(int a, int b) { return a >= 0 ? a % b : a - (b * CEIL(a, b)); }             //always return positive num
int bpm(int a, int b) {                                                             //return x^y in order(log(y))
  int res = 1;
  for (a %= MOD; b; a = a * a % MOD, b >>= 1)
    if (b & 1) res = res * a % MOD;
  return res;
}
int gcd(int a, int b) { return (b ? gcd(b, a % b) : a); }

class BMAXMin {
public:
  static void solve(istream &cin, ostream &cout) {
    int N;
    cin>>N;
    vector<int> a(N);
    rep(i, N)cin>>a[i];
    rep(i, N-1){
      a[i+1] = gcd(a[i], a[i+1]);
    }
    cout<<a[N-1]<<endl;
  }
};

signed main() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio(false);
  cout<<fixed<<setprecision(15);
  BMAXMin solver;
  std::istream& in(std::cin);
  std::ostream& out(std::cout);
  solver.solve(in, out);
  return 0;
}

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

typedef long long ll;
typedef long double ld;
typedef vector<vector<int>> Graph;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
#define pi 3.14159265359
#define inf 2147483647
#define INF 9223372036854775807
#define mod 1000000007
#define mod2 998244353

int gcd(int n, int m) {
	if(n < m) swap(n, m);
	if(n % m == 0) return m;
	return gcd(m, n % m);
}

int main() {
	int N; cin >> N;
	vector<int> a(N);
	for(int i = 0; i < N; i++) cin >> a[i];
	int G = a[0];
	for(int i = 1; i < N; i++) G = gcd(G, a[i]);
	cout << G << endl;
}


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

#define ll long long int

#define pi 2*acos(0.0)
#define mod 1000000007

#define fast   ios_base::sync_with_stdio(false);cin.tie(NULL);

#define pii pair<ll,ll>

#define pb push_back

#define Bit_off(val,pos)       (val & (~(1<<pos)))
#define Bit_on(val,pos)        (val | (1<<pos))
#define Bit_toggle(val,pos)    (val ^ (1<<pos))
#define Bit_check(val,pos)     (bool)(val & (1<<pos))
#define odd_even(val)          (bool)(val & 1)
#define koita_1_ase(val)       (__builtin_popcount(val))

//ll Big_Mod(ll v1, ll p, ll md)  { ll res=1; v1=v1%md; while (p > 0){if (p & 1)res = (res * v1) % md; p =p>>1; v1 = (v1 * v1) % md;}return res;}
ll ar[500009],cr[500009],br[500009],tr[500009];
ll fx[]= {-1,1,0,0};
ll fy[]= {0,0,1,-1};

map<ll,ll>mp,mp1,mp2;
vector<ll>v[500009],v1;
string s,q;

struct evan
{
    ll l,r,w;

} st[500009];

bool com(evan a,evan b)
{
    return a.r<b.r;
}

int main()
{
    fast;
    ll a,b,c,d,e,i,j,k,x,y,z,f,g,h,n,m;

    cin>>n>>x>>s;
    for(i=0; i<n; i++)
    {
        if(s[i]=='o')
        {
            x++;
        }
        else
        {
            if(x)
            {
                x--;
            }
        }
    }
    cout<<x<<endl;
}

#include<map>
#include<ctime>
#include<cstdio>
#include<cctype>
#include<string>
#define ll long long
const ll N=1e3+10;
const ll HgS=1e9+7;
using namespace std;
ll read() {
	char c;
	ll x=0,f=1;
	while(!isdigit(c=getchar()))
		f-=2*(c=='-');
	while (isdigit(c)){
		x=x*10+(c-48)*f;
		c=getchar();
	}
	return x;
}
ll n,f,res;
ll fib(ll n){
	ll a=0,b=1,c=0;
	for(ll i=1;i<=n;++i){
		c=(a+b)%HgS;
		a=b;
		b=c;
	}
	return a;
}
int main() {
	#ifndef ONLINE_JUDGE
	freopen("D.in","r",stdin);
	freopen("D.out","w",stdout);
	#endif
	clock_t t1=clock();
	//--------
	n=read();
	for(int i=0;i<4;++i){
		char c;
		while(!isalpha(c=getchar()));
		f<<=1;
		f|=(c=='B');
	}
	switch(f){
		case 0:
		case 1:
		case 2:
		case 3:
		case 5:
		case 7:
		case 13:
		case 15:
			res=1;
			break;
		case 4:
		case 10:
		case 11:
		case 12:
			res=1;
			for(int i=4;i<=n;++i){
				res<<=1;
				res%=HgS;
			}
			break;
		default:
			res=fib(n-1);
			break;
	}
	printf("%lld",res);
	//--------
	clock_t t2=clock();
	fprintf(stderr,"time:%0.3lfs",1.0*(t2-t1)/CLOCKS_PER_SEC);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define nl '\n'
typedef long long ll;
#define f(i,start,end) for(i=start;i<=end;i++)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define piii pair<pii,int>
#define F first
#define S second
#define min_heap priority_queue<ll, vector<ll>, greater<ll> >
#define max_heap priority_queue<ll>
#define min_heap_pair priority_queue<pii, vector<pii>, greater<pii> >
#define eb emplace_back
#define mapGreater map<int, int, greater<int> >
//#define pi 3.14159265
#define printAr(a, n) f(i, 0, n-2) cout << a[i] << ' '; cout << a[n-1] << nl;

// Implementation of Ordered Set - PBDS
/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree< int,
              null_type,
              less<int>,
              rb_tree_tag,
              tree_order_statistics_node_update
            > ordered_set;
*/

inline bool pair_cmp(pii p1, pii p2)
{
    if(p1.S!=p2.S) return p1.S<p2.S;
    return p1.F<p2.F;
}

const int64_t INF = 1e18+7;
inline int64_t mul(int64_t a, int64_t b){
    return (INF/a>b? a*b: INF);
}
inline int64_t add(int64_t a, int64_t b){
    return (INF-a>b? a+b: INF);
}

//sieve of eratosthenes

bool p[1000001];
void sieve()
{
    //all odds + falses are primes (>= 2)
    for(int i=4; i<=1000000; i+=2)
        p[i] = 1;
    for(int i=3; i*i<=1000000; i+=2)
    {
        if(!p[i])
        {
            for(int j=i*i; j<=1000000; j+=(2*i))
            {
                p[j] = 1;
            }
        }
    }
}

void solve()
{
    int i=0, j=0;
    string s; cin >> s;
    int n = s.size();
    f(i, 0, n-4+1)
    {
        if(s.substr(i,4)=="ZONe") j++;
    }
    cout << j << nl;
}

int main()
{
    ios::sync_with_stdio(0); cin.tie(0); //fastio;
    //sieve();
    //int t=0,tc=0; cin >> tc; for(t=1; t<=tc; ++t)
    {
        //cout << "Case " << t << ": ";
        solve();
        //if(t<tc) cout << '\n';
    }
    return 0;
}

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int main()
{
	string str;
	cin >> str;
	int num=0;
	int index=0;
	string sub="ZONe";
	while( (index=str.find(sub,index)) < str.length() ){
		num++;
		index++;
	}
	cout << num << endl;
	return 0;
 }


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

template<typename T>
void out(T x) { cout << x << endl; exit(0); }
#define watch(x) cout << (#x) << " is " << (x) << endl

using ll = long long;
const ll mod = 1e9 + 7;

void add(ll &x, ll y) {
    x %= mod;
    y %= mod;
    x += y;
    x %= mod;
}

ll pw(ll x, ll y) {
    ll res=1;
    while (y) {
	if (y%2) res=res*x%mod;
	x=x*x%mod;y=y/2;
    }
    return ((res%mod)+mod)%mod;
}

const int maxn = 1005;

int A = 0;
int B = 1;

int n;
int AA, AB, BA, BB;

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

    cin>>n;
    char tmp;

    cin>>tmp;
    AA=int(tmp-'A');

    cin>>tmp;
    AB=int(tmp-'A');

    cin>>tmp;
    BA=int(tmp-'A');

    cin>>tmp;
    BB=int(tmp-'A');

    if (n==2) out(1);

    assert(n>=3);

    if (AB==B) {
	swap(AA, BB);
	swap(A, B);
    }

    assert(AB == A);
    if (AA==A) out(1);

    assert(AB == A && AA == B);

    if (BA == A) {
	// BB isn't possible
	vector<ll> dp(n+1, 0);
	dp[0]=1;
	dp[1]=1;
	dp[2]=2;
	for (int i=2; i<=n; i++) {
	    dp[i]=(dp[i-1]+dp[i-2])%mod;
	}
	//A....B

	out(dp[n-2]);
    }

    assert(AB == A && AA == B && BA == B);

    //A.....AB
    //second to last character has to be A.

    cout<<pw(2,n-3)<<endl;
    return 0;
}

#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#include <complex>
#include <vector>
#include <limits>
#include <iomanip>
#include <cassert>
#include <numeric>
#include <chrono>
#include <random>

using namespace std;

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

#define debug(x) cerr << #x << " = " << (x) << endl;
#define debug_pii(x) cerr << "(" << x.first << "," << x.second << ")";
#define rep(i, n) for(int i = 0;i < n;i++)
#define pb push_back
#define F first
#define S second

// template<typename _Ty1, typename _Ty2>
// ostream& operator<<(ostream& _os, const pair<_Ty1, _Ty2>& _p) {
//     _os << '(' <<_p.first << ',' << _p.second << ')';
//     return _os;
// }
//
// template<typename _Ty1, typename _Ty2>
// istream& operator>>(istream& _is, pair<_Ty1, _Ty2>& _p) {
//     _is >> _p.first >> _p.second;
//     return _is;
// }

int n,m;
const ll mod = 998244353;
vector<ll> inv{0, 1}; // ith index will store (1/i)%mod
vector<ll> finv{1, 1}; // ith index will store (1/i!)%mod
vector<ll> fact{1, 1}; // ith index will store (i!)%mod

void populate2(int n) {
    for(int i = 2;i < n;i++) {
        fact.pb((i*fact[i-1])%mod);
        inv.pb(mod-((inv[mod%i]*(mod/i))%mod));
        finv.pb((finv[i-1]*inv[i])%mod);
    }
}

ll P(int n, int r) {
  return fact[n]*finv[n-r]%mod;
}

ll C(int n, int r) {
  if(n < r) return 0;
  return P(n, r)*finv[r]%mod;
}

ll dp[13][5001];

void solve() {
  cin>>n>>m;
  populate2(n+10);
  // dp[bit][sum]
  int bit = 12;
  dp[bit][0]=1;

  for(bit -= 1;bit >= 0;bit--) {
    for(int j = 0;j <= m;j++) {
      int k = 0;
      for(;k <= n;k+=2) {
        if(j - (1<<bit)*1LL*k >= 0) {
          dp[bit][j] += dp[bit+1][j - (1<<bit)*1LL*k]*C(n,k)%mod;
          dp[bit][j] %= mod;
        }
      }
    }
  }

  cout<<dp[0][m]<<endl;

}

// 2 10 5 15 30
// ABABABA A

// + - - - - + - - - - - + - - - - - + - - - - - + - - - == N
// M
// + 1
// ++
// +++
// ++++
// +++++
// ++++++
// .
// .        (i)
// .
// +++++++++++++ 20
//
// dp[i][val] //

// at max 20 distinct # in the sequence

int main() {

 // freopen("input.in","r",stdin);
 // freopen("output.out","w",stdout);
 // cout << fixed << setprecision(15);

 ios_base::sync_with_stdio(false);
 cin.tie(nullptr);

 int t = 1;
 // cin >> t;
 while (t--) {
   solve();
 }

 return 0;
}


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

int main(){
    long N,K;
    cin >> N >> K;

    rep(i,K){
        if(N%200 ==0){
            N /=200;
        }
        else{
            N = N*1000+200;
        }
    }

    cout << N << endl;
}

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

#define endl		'\n'
#define w(t)		int t;cin>>t;while(t--)
#define int			long long
#define fr(i,a,b)	for(int i=a;i<=b;i++)
#define rep(i,a,b)	for(int i=a;i<b;i++)
#define pb 			push_back
#define ppb			pop_back
#define mp			make_pair
#define all(x)		x.begin(),x.end()
#define ff			first
#define ss			second
#define pii			pair<int,int>
#define vi			vector<int>
#define vvi			vector<vi>
#define pqi			priority_queue<int>
#define pqd			priority_queue<int,vi,greater<int>>
#define inf			1e18
#define mod			1000000007
#define PI 			3.14159265358979323846264338327950288419716939937510

int32_t main() {

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

	int n,k;
	cin>>n>>k;
	rep(i,0,k){
		if(n%200==0)
			n/=200;
		else{
			n*=1000;
			n+=200;
		}
	}

	cout<<n<<endl;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> P;
typedef vector<ll> VI;
typedef vector<VI> VVI;
#define REP(i,n) for(int i=0;i<(n);i++)
#define ALL(v) v.begin(),v.end()
constexpr ll MOD=998244353;
constexpr ll INF=1e18;

ll power(ll x, ll y){
    x%=MOD;
    ll ret=1;
    while(y){
        if(y&1) ret=ret*x%MOD;
        x=x*x%MOD;
        y>>=1;
    }
    return ret;
}

int main(){
    int h, w, k; cin >> h >> w >> k;
    vector<vector<char>> f(h,vector<char>(w,'.'));
    int x, y; char c;
    REP(i,k){
        cin >> x >> y >> c;
        x--, y--;
        f[x][y]=c;
    }
    VVI dp(h+1,VI(w+1,0));
    dp[0][0]=power(3,h*w-k);
    ll p=power(3,MOD-2);
    REP(i,h)REP(j,w){
        if(f[i][j]=='.'&&!(i==0&&j==0))
            dp[i][j]=dp[i][j]*p%MOD;
        if(f[i][j]=='.'){
            dp[i+1][j]=(dp[i+1][j]+dp[i][j]*2)%MOD;
            dp[i][j+1]=(dp[i][j+1]+dp[i][j]*2)%MOD;
        }
        else if(f[i][j]=='R'){
            dp[i][j+1]=(dp[i][j+1]+dp[i][j])%MOD;
        }
        else if(f[i][j]=='D'){
            dp[i+1][j]=(dp[i+1][j]+dp[i][j])%MOD;
        }
        else{
            dp[i+1][j]=(dp[i+1][j]+dp[i][j])%MOD;
            dp[i][j+1]=(dp[i][j+1]+dp[i][j])%MOD;
        }
    }
    cout << dp[h-1][w-1] << endl;
    return 0;
}


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

using namespace std;

const int mod = 1000000007;
const int kMaxN = 200200;

int k, n;
char s[kMaxN];
long long a[kMaxN];
long long dp[kMaxN][20];

int Cnt(int x) {
  int cnt = 0;
  while (x) {
    cnt += x & 1;
    x >>= 1;
  }
  return cnt;
}
int main() {
  scanf("%s%d", s, &k);
  int n = strlen(s);
  for (int i = 0; i < n; i++) {
    if (s[i] >= 'A' && s[i] <= 'F') {
      a[i] = s[i] - 'A' + 10;
    } else {
      a[i] = s[i] - '0';
    }
  }
  dp[1][1] = a[0] - 1;
  long long num = 1ll << a[0];
  for (int i = 1; i < n; i++) {
    for (int j = 1; j <= 16; j++) {
      dp[i + 1][j] = (dp[i + 1][j] + dp[i][j] * j) % mod;
      dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j] * (16 - j)) % mod;
    }
    dp[i + 1][1] = (dp[i + 1][1] + 15) % mod;
    for (int j = 0; j < a[i]; j++) {
      dp[i + 1][Cnt(num | 1ll << j)] = (dp[i + 1][Cnt(num | 1ll << j)] + 1) % mod;
    }
    num |= 1ll << a[i];
  }
  if (Cnt(num) == k) {
    printf("%lld", (dp[n][k] + 1) % mod);
  } else {
    printf("%lld", dp[n][k]);
  }
}


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

int main(){
    int H,W;
    cin>>H>>W;
    vector<string> S(H);
    for(int i=0;i<H;i++) cin>>S[i];
    vector<int> r(H+W,0),b(H+W,0),w(H+W,0);
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            if(S[i][j]=='R') r[i+j]++;
            if(S[i][j]=='B') b[i+j]++;
            if(S[i][j]=='.') w[i+j]++;
        }
    }
    ll ans=1;
    for(int i=0;i<H+W;i++){
        if(r[i]>0&&b[i]>0) ans=0;
        if(w[i]>0&&r[i]==0&&b[i]==0) ans*=2;
        ans%=mod;
    }
    cout<<ans<<endl;
    return 0;
}

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <array>
#include <random>
#include <cmath>
#include <list>
#include <ctime>
#include <sstream>
#include <queue>
#include <climits>
#include <stack>
#include <random>
#include <bitset>
#include <numeric>
#include <cassert>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef long long ll;
#define rep(x, b, e) for(int x=(b); x<(e); ++x)
#define trav(a, x) for(auto& a : x)
#define ford(x, b, e) for(int x=((int)(b))-1; x>=(e); --x)
#define all(c) c.begin(),c.end()
#define sz(x) ((int)((x).size()))
#define pb push_back
#define st first
#define nd second
#define mp(x,y) make_pair(x,y)
typedef short int sint;

#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	int h, w;
	cin >> h >> w;
	vector<string> s(h);
	rep(i, 0, h) {
		cin >> s[i];
	}
	const int MOD = 998244353;
	ll res = 1;
	rep(i, 0, w + h - 1) {
		// printf("for sum: %d:\n", i);
		int r1 = i < h ? i : h - 1;
		int c1 = i - r1;
		bool has_dot = false, has_r = false, has_b = false;
		rep(j, 0, min(r1 + 1, w - c1)) {
			int nr1 = r1 - j;
			int nc1 = c1 + j;
			// printf("checking: %d, %d\n", nr1, nc1);
			if (s[nr1][nc1] == 'R') {
				has_r = true;
			} else if (s[nr1][nc1] == 'B') {
				has_b = true;
			} else {
				has_dot = true;
			}
		}
		if (has_r && has_b) {
			cout << 0 << endl;
			return 0;
		}
		if (!has_r && !has_b) {
			res = (res * 2) % MOD;
		}
	}
	cout << res << endl;
}


#include<bits/stdc++.h>
#define ll long long int
#define M 1000000007
#define mod 998244353
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define pi pair<ll,ll>
#define endl "\n"
using namespace std;
const ll N=200010;

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

    ll n,m,x,y;
    cin>>n>>m>>x>>y;

    vector<pi> val;
    vector<pi> adj[n+1];

    for(ll i=0;i<m;++i){
        ll a,b,t,k;
        cin>>a>>b>>t>>k;
        adj[a].pb(mp(b,i));
        adj[b].pb(mp(a,i));
        val.pb(mp(t,k));
    }

    vector<ll> dis(n+1,LLONG_MAX);

    set<pi> s;
    s.insert(mp(0,x));

    while(!s.empty()){
        ll v=(*s.begin()).second;
        ll d=(*s.begin()).first;
        s.erase(s.begin());
        if(d>=dis[v]){
            continue;
        }
        dis[v]=d;
        for(auto x:adj[v]){
            ll u=x.first;
            ll idx=x.second;
            ll k=val[idx].second;
            ll t=val[idx].first;
            ll cost=d+t;
            if(d%k!=0){
                cost+=(k-d%k);
            }
            if(cost<dis[u]){
                s.insert(mp(cost,u));
            }
        }
    }

    if(dis[y]==LLONG_MAX){dis[y]=-1;}
    cout<<dis[y];

    return 0;
}

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

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

#define rep(i,cc,n) for(int i=cc;i<n;++i)
#define lrep(i,cc,n) for(long long i=cc;i<n;++i)
#define sqrep(i,cc,n) for(long long i=cc;i*i<=n;++i)
#define rrep(i,cc,n) for(int i=cc;i>=n;--i)
#define pii pair<int, int>
#define pll pair<long long, long long>

using ll = long long;

const vector<int> dx = {1, 0, 1};
const vector<int> dy = {0, 1, 1};

const vector<int> dx2 = {1, 1,  1, 0,  0, 0, -1, -1, -1};
const vector<int> dy2 = {1, 0, -1, 1, -1, 0,  1,  0, -1};
const double PI = 3.1415926535;
const ll inf = 1001001001;
const ll e9  = 1000000000;
const ll mod = 1000000007;
const ll mod2 = 998244353;

const int MAX = 1000000;
const int MOD = 1000000007;
const ll big = (1ll<<60);

ll gcd(ll x, ll y) { return (x % y)? gcd(y, x % y): y; }

struct Edge {
    ll to;
    ll cost;
    ll k;
};

int main(){
    int n, m, x, y;
    cin >> n >> m >> x >> y;
    x--,y--;
    vector<vector<Edge>>G(n);
    rep(i, 0, m){
      ll a, b;
      ll ti, ki;
      cin >> a >> b >> ti >> ki;
      a--,b--;
      Edge ed1, ed2;
      ed1.to = b;
      ed1.cost = ti;
      ed1.k = ki;
      G[a].push_back(ed1);

      ed2.to = a;
      ed2.cost = ti;
      ed2.k = ki;
      G[b].push_back(ed2);
    }
    priority_queue<pll,vector<pll>,greater<pll>>que;
    que.emplace(0,x);
    vector<ll>time(n, big);
    vector<bool>visit(n,false);
    time[x] = 0;
    while(!que.empty()){
      pll temp = que.top();
      que.pop();
      if(visit[temp.second])continue;
      visit[temp.second] = true;

      if(time[temp.second]<temp.first)continue;
      for(auto p:G[temp.second]){
        ll temp_time = ((temp.first+p.k-1)/p.k)*p.k + p.cost;
        if(time[p.to]>temp_time){
          time[p.to] = temp_time;
          que.push({time[p.to],p.to});
        }
      }
    }
    if(time[y]==big){
      cout << -1 << endl;
    }else cout << time[y] << endl;
}


#include <iostream>

using namespace std;
using ll = long long;

int MOD = 1e9 + 7;

ll my_pow(ll x, ll n) {
  if (n == 0) {
    return 1;
  }
  else if (n % 2 == 0) {
    return my_pow(x * x % MOD, n >> 1);
  } else {
    return x * my_pow(x, n - 1) % MOD;
  }
}

int main(void){
  int N, P;

  cin >> N >> P;

  ll ans = P - 1;

  ans = ans * my_pow(P - 2, N - 1) % MOD;

  cout << ans << endl;

  return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef vector<ll> vl;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<char> vc;
typedef queue<ll> ql;
typedef deque<ll> dql;
typedef priority_queue<ll> pql;
typedef set<ll> sl;
typedef pair<ll, ll> pl;
typedef map<ll, ll> ml;
typedef vector<vl> vvl;
typedef vector<pl> vpl;
#define rep(i, n) for(ll i = 0; i < ll(n); i++)
#define rep2(i, k, n) for(ll i = ll(k); i <= ll(n); i++)
#define rep3(i, n, k) for(ll i = ll(n); i >= ll(k); i--)
#define all(v) (v).begin(), (v).end()
ll mod(ll a, ll b) {return (a % b + b) % b;}
ll quo(ll a, ll b) {return (a - mod(a, b)) / b;}
template <typename T, typename U> bool chmin(T &a, const U b) {if(a > b) {a = b; return 1;} return 0;}
template <typename T, typename U> bool chmax(T &a, const U b) {if(a < b) {a = b; return 1;} return 0;}
const ll INF = 1LL << 60;
const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;
const ll MAX = 2e5;
const ld eps = 1e-9;
const char newl = '\n';

struct mint{
  ll val;
  mint() {}
  mint(ll x) {val = mod(x, MOD);}
  mint operator-() {return mint(-this->val);}
  bool operator==(mint a) {return this->val == a.val;}
  bool operator<(mint a) {return this->val < a.val;}
  bool operator!=(mint a) {return this->val != a.val;}
  mint operator+(mint a) {return mint(this->val + a.val);}
  mint operator-(mint a) {return mint(this->val - a.val);}
  mint operator*(mint a) {return mint(this->val * a.val);}
  mint operator/(mint a) {return mint(this->val * a.inv().val);}
  mint &operator+=(mint a) {return *this = *this + a;}
  mint &operator-=(mint a) {return *this = *this - a;}
  mint &operator*=(mint a) {return *this = *this * a;}
  mint &operator/=(mint a) {return *this = *this / a;}
  friend istream &operator>>(istream &is, mint &m) {
    is >> m.val;
    return is;
  }
  friend ostream &operator<<(ostream &os, mint &m) {
    os << m.val;
    return os;
  }
  mint pow(ll n) {
    if(n == 0) return 1;
    if(n & 1) return pow(n-1) * *this;
    mint ret = pow(n/2);
    return ret * ret;
  }
  vector<mint> powv(ll n) {
    vector<mint> vec(n+1, 1);
    rep2(i, 1, n) vec[i] = vec[i-1] * *this;
    return vec;
  }
  mint inv() {return pow(MOD-2);}
  vector<mint> invv(ll n) {
    vector<mint> vec(n+1, 1);
    rep2(i, 2, n) vec[i] = -vec[MOD%i] * (MOD/i);
    return vec;
  }
};

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

  ll n, p;
  cin >> n >> p;
  mint ans = mint(p-1)*(mint(p-2).pow(n-1));
  cout << ans << newl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long int;
using ld = long double;
#define pow(n,m) powl(n,m)
#define sqrt(n) sqrtl(n)
const ll MAX = 5000000000000000000;
const ll MOD = 1000000007;
//998244353;
void randinit(){srand((unsigned)time(NULL));}
int main(){
    ll N;
    cin >> N;
    string S,T;
    cin >> S >> T;
    if(S == T){
        cout << 0 << endl;
        return 0;
    }
    ll a = 0,b = 0;
    for(ll i = 0;i < N;i++) a += (S[i] == '0');
    for(ll i = 0;i < N;i++) b += (T[i] == '0');
    if(a != b){
        cout << "-1" << endl;
        return 0;
    }
    vector<ll> A(N,-1),B(N,-1);
    ll c = 0;
    for(ll i = 0;i < N;i++){
        if(S[i] == '0'){
            A[i] = c;
            c++;
        }
    }
    c = 0;
    for(ll i = 0;i < N;i++){
        if(T[i] == '0'){
            B[i] = c;
            c++;
        }
    }
    for(ll i = 0;i < N;i++){
        if(S[i] == '0' && A[i] == B[i]) a--;
    }
    cout << a << endl;
}

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

#define fi first
#define se second

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

string s;
map<char,int> cnt;

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> s;
    ll ans = 0;
    for (int i = s.length()-1; i >= 1; i--) {
        if (s[i] == s[i-1]) {
            ans += s.length()-i-1-cnt[s[i]];
            cnt.clear();
            cnt[s[i]] = s.length()-i-1;
        }
        cnt[s[i]]++;
    }
    cout << ans << '\n';
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i=a; i<=b; i++)
#define repd(i, a, b) for(int i=a; i>=b; i--)
#define vi vector<int>
#define vll vector<long long>
#define pii pair<int,int>
#define pll pair<long long,long long>
#define pb push_back
#define fr first
#define sc second
#define vb vector<bool>

typedef long long ll;
typedef unsigned long long ull;

/*struct cmp {
    bool operator()(const pair<int, pii> &p1, const pair<int, pii> &p2) {
        return p1.fr > p2.fr;
    }
};*/

void google(){
	static int tc=1;
	cout<<"Case #"<<tc<<": ";
	tc++;
}

int n;

ll fun(vll &v1,vll &v2){
	ll ans=1e18;
	bool ok=0;
	if(v1.size()>v2.size()){
		swap(v1,v2);
		ok=1;
	}
	for(int i=0;i<v1.size();i++){
		int id=lower_bound(v2.begin(),v2.end(),v1[i])-v2.begin();
		ans=min(ans,abs(v2[id]-v1[i]));
		if(id!=0) id--;
		ans=min(ans,abs(v2[id]-v1[i]));
	}
	if(ok) swap(v1,v2);
	return ans;
}

void solve(int tc = 1) {
	vll v[3];
	for(int i=0;i<2*n;i++){
		ll a;
		char ch;
		cin>>a>>ch;
		if(ch=='R'){
			v[0].pb(a);
		}
		else if(ch=='G'){
			v[1].pb(a);
		}
		else{
			v[2].pb(a);
		}
	}

	ll ans=1e18;

	for(int i=0;i<3;i++) sort(v[i].begin(),v[i].end());

	if(v[0].size()%2==0 && v[1].size()%2==0 && v[2].size()%2==0){
		cout<<0<<endl;
		return;
	}

	if(v[0].size()%2==0){
		ans=min(ans,fun(v[1],v[2]));
		ans=min(ans,fun(v[1],v[0])+fun(v[2],v[0]));
	}
	else if(v[1].size()%2==0){
		ans=min(ans,fun(v[0],v[2]));
		ans=min(ans,fun(v[1],v[0])+fun(v[2],v[1]));
	}
	else{
		ans=min(ans,fun(v[1],v[0]));
		ans=min(ans,fun(v[1],v[2])+fun(v[2],v[0]));
	}
	cout<<ans<<endl;
}

int main() {
/*#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif*/
    ios::sync_with_stdio(false);
    cin.tie(0);
    //cout << setprecision(16) << fixed;
    int t = 1;
    // cin >> t;
    int tc=0;

    while (t--) {
    	cin>>n;
        tc++;
        solve(tc);
    }
}

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

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

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

//i_am_noob
//#define wiwihorz
int n;
vector<int> vec[3];

int solve(int x, int y){
    int res=inf;
    for(auto i: vec[x]) if(sz(vec[y])&&i<=vec[y].back()) res=min(res,(*lower_bound(all(vec[y]),i))-i);
    for(auto i: vec[y]) if(sz(vec[x])&&i<=vec[x].back()) res=min(res,(*lower_bound(all(vec[x]),i))-i);
    return res;
}

void orzck(){
    cin >> n;
    rep(2*n){
        int x;
        char c;
        cin >> x >> c;
        if(c=='R') vec[0].pb(x);
        else if(c=='G') vec[1].pb(x);
        else vec[2].pb(x);
    }
    rep(3) sort(all(vec[i]));
    vector<int> vec1;
    rep(3) if(sz(vec[i])%2==0) vec1.pb(i);
    if(sz(vec1)==3){
        print(0);
        return;
    }
    int x,y,z;
    x=vec1[0];
    y=(x+1)%3;
    z=3-x-y;
    print(min(solve(y,z),solve(x,y)+solve(x,z)));
}

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


#include <cstdio>

#define rep( i, a, b ) for( int (i) = (a) ; (i) <= (b) ; ++ (i) )
#define per( i, a, b ) for( int (i) = (a) ; (i) >= (b) ; -- (i) )

const int mod = 1e9 + 7;
const int MAXN = 2e3 + 5;

template<typename _T>
void read( _T &x )
{
	x = 0; char s = getchar(); int f = 1;
	while( s < '0' || '9' < s ) { f = 1; if( s == '-' ) f = -1; s = getchar(); }
	while( '0' <= s && s <= '9' ) { x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ); s = getchar(); }
	x *= f;
}

template<typename _T>
void write( _T x )
{
	if( x < 0 ) putchar( '-' ), x = -x;
	if( 9 < x ) write( x / 10 );
	putchar( x % 10 + '0' );
}

int A[MAXN];
int N, M;

int Mul( long long x, int v ) { return x * v % mod; }

int Qkpow( int base, int indx )
{
	int ret = 1;
	while( indx )
	{
		if( indx & 1 ) ret = Mul( ret, base );
		base = Mul( base, base ), indx >>= 1;
	}
	return ret;
}

int Inv( const int a ) { return Qkpow( a, mod - 2 ); }

int main()
{
	read( N ), read( M ); int su = 0;
	rep( i, 1, N ) read( A[i] ), su += A[i];
	int prod = 1;
	rep( i, 1, su + N ) prod = Mul( prod, Mul( Inv( i ), M + N - i + 1 ) );
	write( prod ), putchar( '\n' );
	return 0;
}

#include<bits/stdc++.h>
#define it register int
#define ct const int
#define il inline
using namespace std;
const int N=1000005;
int p[N],cn,mn[N],n;
bool isp[N];
il int Min(ct p,ct q){return p<q?p:q;}
il void Pre(){
	it i,j,x;mn[1]=1;
	for(i=2;i<=n;++i){
		if(!isp[i]) p[++cn]=i,mn[i]=i;
		for(j=1;(x=p[j]*i)<=n;++j){
			isp[x]=1,mn[x]=Min(mn[i],p[j]);
			if(!(i%p[j])) break;
		}
	}
}
int main(){
	scanf("%d",&n),Pre();
	for(it i=1,j;i<=n;++i){
		it cnt=0;
		for(j=i;j>1;){
			it x=mn[j];
			while(j>1&&mn[j]==x) j/=x,++cnt;
			//++cnt;
		}
		printf("%d ",cnt+1);
	}
	return 0;
}


#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
// #define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
template<typename T>
void __p(T a) {
	cout << a;
}
template<typename T, typename F>
void __p(pair<T, F> a) {
	cout << "{";
	__p(a.first);
	cout << ",";
	__p(a.second);
	cout << "}";
}
template<typename T>
void __p(std::vector<T> a) {
	cout << "{";
	for (auto it = a.begin(); it < a.end(); it++)
		__p(*it), cout << ",}"[it + 1 == a.end()];
}
template<typename T, typename ...Arg>
void __p(T a1, Arg ...a) {
	__p(a1);
	__p(a...);
}
template<typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
	cout << name << " : ";
	__p(arg1);
	cout << endl;
}
template<typename Arg1, typename ... Args>
void __f(const char *names, Arg1 &&arg1, Args &&... args) {
	int bracket = 0, i = 0;
	for (;; i++)
		if (names[i] == ',' && bracket == 0)
			break;
		else if (names[i] == '(')
			bracket++;
		else if (names[i] == ')')
			bracket--;
	const char *comma = names + i;
	cout.write(names, comma - names) << " : ";
	__p(arg1);
	cout << " | ";
	__f(comma + 1, args...);
}
#define trace(...) cout<<"Line:"<<__LINE__<<" ", __f(#__VA_ARGS__, __VA_ARGS__);
#else
#define trace(...)
#endif
typedef long long int ll;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
typedef pair<ll , ll> pp;
typedef pair<pair<ll, ll>, ll> ppp;
#define X first
#define Y second
#define getones(n) __builtin_popcountll(n)
#define debug(x) cout<<#x<<" :: "<<x<<"\n";
#define debug2(x,y) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\n";
#define debug3(x,y,z) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<"\n";
#define fastIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define frv(i,a,b) for (ll i = (a), _b = (b); i < _b; i++)
#define frrv(i,a,b) for (ll i = (a), _b = (b); i >= _b; i--)
#define fr(i,n) for (ll i = 0, _n = (n); i < _n; i++)
#define frr(i,n) for (ll i = n - 1; i >= 0; i--)
#define fordata(it,ar) for (auto it = ar.begin(); it != ar.end(); it++)
#define fill(ar,val) fr(i,sizeof(ar)/sizeof(ll)) ar[i]=val
#define fill2(ar,val) fr(i,sizeof(ar)/sizeof(ar[0])) fr(j,sizeof(ar[0])/sizeof(ll)) ar[i][j]=val
#define fill0(ar) memset(ar,0,sizeof(ar))
#define sz(x) (int)x.size()
#define len(x) (int)x.length()
#define all(ar) ar.begin(), ar.end()
#define INF 1000000000000000000
#define PI 3.14159265358979323846L
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
const ll N = 1e6 + 1;
const ll K = 1e9 + 7;
#define vv vector<ll>
const ll globalmod = 1e9 + 9;
int main() {
	ll a, b, x, y;
	cin >> a >> b >> x >> y;
	if (a > b) {
		cout << min(x + (a - b-1)*y, (max(2 * (a - b) - 1, 0ll))*x);
	}
	else {
		cout << min(x + (b - a)*y, (2 * (b - a) + 1)*x);
	}
}

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <array>
#include <climits>
using namespace std;
typedef long long unsigned int unsigned_myint;
typedef long long int myint;

int main(){
myint r_1,c_1,r_2,c_2,r_d,c_d;
int ans;
 cin >>  r_1;
 cin >> c_1;
 cin >> r_2;
 cin >> c_2;
    r_d=r_2-r_1;
    c_d=c_2-c_1;
    if((r_1==r_2) && (c_1==c_2)){
        ans=0;
    }else if(((r_1+c_1)==(r_2+c_2))||((r_1-c_1)==(r_2-c_2)||(abs(c_2-c_1)+abs(r_2-r_1)<=3))){
        ans=1;
    }else if(abs(r_d-c_d)<=3 || abs(-r_d-c_d)<=3||abs(-r_d+c_d)<=3||abs(r_d+c_d)<=3||((c_1+r_1)%2==(c_2+r_2)%2)){
        ans =2;
    }else{
        ans =3;
    }
    cout << ans<< endl;

}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> iint;
typedef pair<ll,ll> llll;
#define ALL(x) (x).begin(),(x).end()
const ll zero = 0;
const ll one = 1;
const ll INF = 9223372036854775807; //10^18
const int inINF = 2147483647; //10^9
const ll MOD = 1000000007; //10^9+7
const ll MOD2 = 998244353;
void Yes() {printf("Yes\n");}
void No() {printf("No\n");}
void YES() {printf("YES\n");}
void NO() {printf("NO\n");}

void solve(){
    int N;
    cin >> N;
    vector<ll> a(N);
    for (int i = 0; i < N; i++) {
        cin >> a[i];
    }
    if(N % 2 == 0){
        map<ll, int> m;
        for (int i = 0; i < N; i++) {
            if(m.count(a[i])){
                m[a[i]]++;
            }
            else{
                m[a[i]] = 1;
            }
        }
        for (auto v : m){
            if(v.second % 2 == 1){
                printf("First\n");
                return;
            }
        }
        printf("Second\n");
        return;
    }
    else{
        printf("Second\n");
        return;

    }

}

int main(){
    int t;
    cin >> t;
    for (int i = 0; i < t; i++) {
        solve();
    }

}

#include<bits/stdc++.h>
#define M_PI       3.14159265358979323846
#define Speed_UP  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define   pb  push_back
#define   ff  first
#define   ss  second
#define sz(x) (int)x.size()
#define all(x) (x).begin(), (x).end()
#warning Remember to change t
inline void setIO();
using namespace std;
typedef long long ll;
typedef long double ld;

int solve(){
  ll n;
  cin>>n;
  ll arr[n];
  for(int i=0;i<n;i++){
    cin>>arr[i];
  }

  // n-1 spaces
  ll ans = 1e10;
  for(ll i=0;i<(1LL<<(n-1));i++){
    ll ored = 0;
    ll xord = 0;

    for(ll j = 0;j<n;j++){
      ored|=arr[j];
      if(((1LL<<j)&i)!=0||j==n-1){
        // cout<<ored<<" ";
        xord^=ored;
        ored = 0;
      }
    }
    // cout<<xord<<"\n";
    ans = min(xord,ans);
  }
  cout<<ans;

  return 0;
  }

int main(){
  Speed_UP

  #ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  #endif

  ll t = 1;
  while(t--){
    solve();
  }
}

inline void setIO(string name="") {
  #ifndef ONLINE_JUDGE
  freopen((name+".in").c_str(), "r", stdin);
  freopen((name+".out").c_str(), "w", stdout);
  #endif
  }


#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=b;i>=a;i--)
const ll INF=0x3f3f3f3f3f3f3f3f,mod=1e9+7;
const int inf=0x3f3f3f3f,maxn=1e5+500;
const double pi=3.1415926535;
bool cmp(ll x,ll y)
{
    return x<y;
}
ll n,m,t,ans,a[2*maxn],b[maxn*2]={0},cnt=0;
int main()
{
   scanf("%lld%lld",&n,&m);
   fo(i,0,m-1)scanf("%lld",&a[i]);
   a[m++]=n+1;
   a[m++]=0;
   sort(a,a+m,cmp);
   ll mi=n;
   fo(i,1,m-1){
       ll x=a[i]-a[i-1];
   if(x&&x!=1)b[cnt++]=x-1,mi=min(mi,x-1);
   }
   if(!mi)ans=0;
   else {
   ans=0;
   fo(i,0,cnt-1)
   {
   //    printf("%lld ",b[i]);
       ans+=b[i]/mi;
       if(b[i]%mi)ans++;
   }

   }
   printf("%lld\n",ans);
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <cstdio>
#include <limits>
#define rep(i,n) for(int i = 0; i < n; ++i)
#define rep1(i,n) for(int i = 1; i <= n; ++i)
using namespace std;
template<class T>bool chmax(T &a, const T &b) { if(a < b){ a = b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if(a > b){ a = b; return 1; } return 0; }
template<class T> inline int  sz(T &a) { return a.size(); }
using ll = long long; using ld = long double;
using pi = pair<int,int>; using pl = pair<ll,ll>;
using vi = vector<int>; using vvi = vector<vi>;
using vl = vector<ll>; using vvl = vector<vl>;
const int inf = numeric_limits<int>::max();
const ll infll = numeric_limits<ll>::max();
int main()
{
  int n,m; cin >> n >> m;
  vvi edge(n, vi(n, 0));
  rep(i,m) {
    int a,b; cin >> a >> b;
    a--; b--;
    edge[a][b] = 1;
    edge[b][a] = 1;
  }

  vi tab((1<<n), 0);
  tab[0] = 1;
  rep(S, (1<<n)) {
    if(tab[S]) {
      rep(i,n) {
	bool f = true;
	rep(j,n) {
	  if((S>>j)&1) {
	    if(!edge[i][j]) f = false;
	  }
	}
	if(f) tab[S|(1<<i)] = 1;
      }
    }
  }

  //  rep(i,sz(tab)) cout << i << ":" << tab[i] << "\n";

  vl dp((1<<n), -1);
  auto rec = [&](auto self, int mask)->int {
    //    cout << bitset<8>(mask) << "\n";
    if(dp[mask] >= 0) return dp[mask];
    if(tab[mask]) return dp[mask] = 1;
    int res = 50;
    for(int i=mask;i>0;i=(i-1)&mask){
      if(i == mask) continue;
      int tmp =  self(self, i) + self(self, mask-i);
      chmin(res, tmp);
    }
    return dp[mask] = res;
  };

  int ans = rec(rec, (1<<n)-1);
  cout << ans << "\n";

  return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
const ll max_N = 100;
const ll max_M = 1000000;
ll n, K, mod, dp[max_N + 5][max_M + 5], G[max_M + 5];
ll read() {
	char c = getchar(); ll ans = 0;
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9') ans = ans * 10 + c - '0', c = getchar();
	return ans;
}
void Write(ll x) {
	if (x < 10) putchar(x + '0');
	else Write(x / 10), putchar(x % 10 + '0');
}
ll add(ll x, ll y) {return (x += y) >= mod ? x - mod : x;}
ll sub(ll x, ll y) {return (x -= y) < 0 ? x + mod : x;}
ll max(ll x, ll y) {return x > y ? x : y;}
ll min(ll x, ll y) {return x < y ? x : y;}
ll calc(ll id) {
	ll sum = 0;
	for (ll i = 0; i <= max_M; i++)
		sum = (sum + dp[id - 1][i] * dp[n - id][i]) % mod;
	return sum;
}
int main() {
	n = read(), K = read() + 1, mod = read(); dp[0][0] = 1;
	for (ll i = 1; i <= n; i++) {
		for (ll j = 0; j <= max_M; j++) G[j] = 0;
		for (ll j = 0; j <= max_M; j++)
			G[j] = add(dp[i - 1][j], (j >= i ? G[j - i] : 0));
		for (ll j = 0; j <= max_M; j++)
			dp[i][j] = sub(G[j], (j >= i * K ? G[j - i * K] : 0));
	}
	for (ll i = 1; i <= n; i++) Write((calc(i) * K + mod - 1) % mod), putchar('\n');
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main () {
  string S;
  cin >> S;
  int n = (int)S.size();
  int fl = n - 1;
  while (fl >= 0 && S[fl] == '0') fl --;
  for (int i = 0; i <= fl; i ++) {
    int j = fl - i;
    if (S[i] != S[j]) {
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;
}

#include<bits/stdc++.h>
using namespace std;
int n , f , las = -1e9;
string s;
int main()
{
	cin >> n >> s;
	if(s[0] != s[n - 1])
	{
		printf("1");
		return 0;
	}
	for(int i = 0 ; i < n ; i++ )
	{
		if(s[i] != s[0])
		{
			f |= (las == (i - 1));
			las = i;
		}
	}
	if(f) printf("2");
	else printf("-1");
	return 0;
}
/*
*/


//
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const int maxn = 3050;
const int maxm = maxn*maxn*4;
int head[maxm],vis[maxm];
char G[maxn][maxn];
int dis[maxm];
struct Edge{
	int f,t,w,next;
	Edge(int f = 0,int t = 0,int w = 0,int next = 0):f(f),t(t),w(w),next(next){}
}edge[maxm];
int cnt;
const int INF = 1e9;
void addedge(int f,int t,int w){
	edge[cnt] = Edge(f,t,w,head[f]);
	head[f] = cnt++;
}
void dijkstra(int s){
	typedef pair <int,int> node;
	priority_queue<node,vector<node>,greater<node> >q;
	for(int i =1;i< maxm;i++)dis[i] = INF;
	dis[s] = 0;
	q.push(make_pair(dis[s],s));
	while(!q.empty()){
		node tmp = q.top();
		q.pop();
		int u = tmp.second;
		if(vis[u])continue;
		vis[u] = 1;
		for(int i = head[u];~i;i = edge[i].next){
			int v = edge[i].t;
			if(dis[v] > dis[u] + edge[i].w){
				dis[v] = dis[u] + edge[i].w;
				if(!vis[v]){
					q.push(make_pair(dis[v],v));
				}
			}
		}
	}
	return;
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	memset(head,-1,sizeof(head));
	int n,m;
	const int B = 2050*2050+1;
	int S = B+100;
	int T = B+101;
	cin >> n >> m;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j <= m;j++){
			G[i][j] = s[j-1];
			if(s[j-1] == 'S')S = i*2010+j;
			if(s[j-1] == 'G')T = i*2010+j;
		}
	}
	for(int i = 1;i <= n;i++){
		for(int j = 1;j <= m;j++){
			if(G[i][j] != '#'){
				for(int k = -1;k <= 1;k++){
					for(int l = -1;l <= 1;l++)if(abs(k+l) == 1){
						int x = i+k,y = j+l;
						if(x < 1 or x > n or y < 1 or y > m)continue;
						if(G[i][j] != '#')addedge(i*2010+j,x*2010+y,2);
					}
				}
			}
			if(G[i][j] >= 'a' and G[i][j] <= 'z'){
				addedge(i*2010+j,B+G[i][j],1);
				addedge(B+G[i][j],i*2010+j,1);
			}
		}
	}
	dijkstra(S);
	if(dis[T] == INF)cout << -1;
	else cout << dis[T]/2;
	return 0;
}

/**
  *  Author: dhruv_gheewala
  *  Problem: __________
  *  Date:   13.12.2020
  *  Time:   17:51:47
**/

#if __has_include("debug.h")
    #include "debug.h"
#else
    #include<bits/stdc++.h>
    using namespace std;

    #define fundri 108
    #define debug(...) 1729
#endif

#define endl '\n'
#define int int64_t

typedef pair<int, int> pii;
typedef vector<int> vi;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int rnd(int l = 0, int r = INT_MAX) {return uniform_int_distribution<int>(l, r)(rng);}

bool in_range(int x, int l, int r) {return l <= x && x <= r;}
template<typename H, typename ...T>void inp(H &head) {cin >> head;}
template<typename H, typename ...T>void inp(H &head, T &...tail) {cin >> head;inp(tail...);}
template<typename T>inline istream &operator >>(istream &in, vector<T> &a) {for(T &x : a)in >> x; return in;}
template<typename T, typename U>inline istream &operator >>(istream &in, pair<T, U> &a) {in >> a.first >> a.second; return in;}

// Multi-Dimension Vector
// Usage: vec<n, data-type> dp(dimention-1, dimention-2, ..., dimention-n, default = data-type())
template<int D, typename T> struct vec : public vector<vec<D - 1, T>>
{
    static_assert(D >= 1, "Vector dimensions must be greater than zero !!");
    template<typename... Args>
    vec(int n = 0, Args... args) : vector<vec<D - 1, T>>(n, vec<D - 1, T>(args...)){}
};

template<typename T> struct vec<1, T> : public vector<T> {vec(int n = 0, T val = T()) : vector<T>(n, val){}};

const int inf = 1e15;
const bool testcases = false;

void init_main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

#ifdef DHRUV_GHEEWALA
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    freopen("debug.txt", "w", stderr);
#endif
}

void solve(int tc)
{
    int n, m;
    cin >> n >> m;

    vi a(m);
    cin >> a;

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

    reverse(a.begin(), a.end());
    a.emplace_back(0);

    reverse(a.begin(), a.end());
    a.emplace_back(n + 1);
    m++;

    int mini = inf;
    for(int i = 1; i <= m; i++) {
        if(a[i] - a[i - 1] > 1)
            mini = min(mini, a[i] - a[i - 1] - 1);
    }

    debug(mini, a);
    int res = 0;
    for(int i = 1; i <= m; i++)
        res += ceil(1.00 * (a[i] - a[i - 1] - 1) / mini);
    cout << res << endl;
}

int32_t main(int32_t argc, char **argv)
{
    init_main();

    int TC = 1;
    if(testcases)
        cin >> TC;

    for(int tc = 1; tc <= TC; ++tc) {
        solve(tc);
        fundri;
    }
    return 0;
}


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

int  main() {
	int n; cin >> n;
	vector<int> a(n);

	for (int i = 0; i < n; i++)
		cin >> a[i];

	vector<int>::iterator iter = max_element(a.begin(), a.end());
	int amax = *iter ;

	long long c = 0, ans = 0, psum = 0;
	for (int i = 0; i <n; i++) {
		psum = 0; c = 0;
		for (int j = 0; j < n; j++) {
			if (0<= a[j]-a[i]) {
				c++;
			}
			else {
				psum = c * a[i];
				if (ans < psum)
					ans = psum;
				c = 0;
			}
		}
		if (c == 0)
			psum = a[i];
		else
			psum = c * a[i];

		if (ans < psum)
			ans = psum;
	}

	cout << ans << endl;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mod = pow(10,9)+7;

int main(){
  ll n;
  cin >> n;
  vector<ll> A(n);
  for(ll i=0; i<n; i++) cin >> A[i];

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

  ll ans = A[0]+1;
  for(ll i=1; i<n; i++){
    ans*= (A[i]-A[i-1])+1;
    ans %= mod;
  }
  cout << ans << endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define db double
#define pii pair<int,int>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define pll pair<ll,ll>
#define ti3 tuple<int,int,int>
#define mat vector<vector<int>>
const int inf = 1 << 30;
const ll linf = 1LL << 62;
const db EPS = 1e-7;
template<class T> void chmin(T& x, T y){if(x > y) x = y;}
template<class T> void chmax(T& x, T y){if(x < y) x = y;}

ll extgcd(ll a, ll b, ll &x, ll &y){
    if(a % b == 0){
        x = 0, y = 1;
        return b;
    }
    ll g = extgcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
}

void solve(){
    ll X, Y, P, Q;
    cin >> X >> Y >> P >> Q;
    ll ans = linf;
    for(ll i = 0; i < Y; i++){
        for(ll j = 0; j < Q; j++){
            ll x, y;
            ll g = extgcd(2LL * (X + Y), P + Q, x, y);
            if((P + j - X - i) % g == 0){
                y *= (P + j - X - i) / g;
                y %= (X + Y) * 2LL / g;
                if(y > 0) y -= (X + Y) * 2LL / g;
                ans = min(ans, -y * (P + Q) + P + j);
            }
        }
    }
    if(ans == linf) cout << "infinity" << endl;
    else cout << ans << endl;
}

int main(){
    int T;
    cin >> T;
    while(T--){
        solve();
    }
    return 0;
}

#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
template<class S, class T> inline S max_L(S a,T b){
  return a>=b?a:b;
}
inline int my_getchar_unlocked(){
  static char buf[1048576];
  static int s = 1048576;
  static int e = 1048576;
  if(s == e && e == 1048576){
    e = fread_unlocked(buf, 1, 1048576, stdin);
    s = 0;
  }
  if(s == e){
    return EOF;
  }
  return buf[s++];
}
inline void rd(int &x){
  int k;
  int m=0;
  x=0;
  for(;;){
    k = my_getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = my_getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
struct MY_WRITER{
  char buf[1048576];
  int s;
  int e;
  MY_WRITER(){
    s = 0;
    e = 1048576;
  }
  ~MY_WRITER(){
    if(s){
      fwrite_unlocked(buf, 1, s, stdout);
    }
  }
}
;
MY_WRITER MY_WRITER_VAR;
void my_putchar_unlocked(int a){
  if(MY_WRITER_VAR.s == MY_WRITER_VAR.e){
    fwrite_unlocked(MY_WRITER_VAR.buf, 1, MY_WRITER_VAR.s, stdout);
    MY_WRITER_VAR.s = 0;
  }
  MY_WRITER_VAR.buf[MY_WRITER_VAR.s++] = a;
}
inline void wt_L(char a){
  my_putchar_unlocked(a);
}
inline void wt_L(long long x){
  int s=0;
  int m=0;
  char f[20];
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    my_putchar_unlocked('-');
  }
  while(s--){
    my_putchar_unlocked(f[s]+'0');
  }
}
template<class S, class T> inline S chmin(S &a, T b){
  if(a>b){
    a=b;
  }
  return a;
}
int N;
int X[20];
int Y[20];
int Z[20];
long long dp[131072][17];
int main(){
  int i, mask;
  rd(N);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=(0);Lj4PdHRW<(N);Lj4PdHRW++){
      rd(X[Lj4PdHRW]);
      rd(Y[Lj4PdHRW]);
      rd(Z[Lj4PdHRW]);
    }
  }
  for(i=(0);i<(1<<N);i++){
    int j;
    for(j=(0);j<(N);j++){
      dp[i][j] = 4611686016279904256LL;
    }
  }
  dp[0][0] = 0;
  for(mask=(0);mask<(1<<N);mask++){
    for(i=(0);i<(N);i++){
      if(dp[mask][i] < 4611686016279904256LL){
        int j;
        for(j=(0);j<(N);j++){
          if(!((mask) &(1<<(j)))){
            chmin(dp[mask|(1<<j)][j], dp[mask][i] + abs(X[i]-X[j]) + abs(Y[i]-Y[j]) +max_L(Z[j]-Z[i], 0));
          }
        }
      }
    }
  }
  wt_L(dp[(1<<N)-1][0]);
  wt_L('\n');
  return 0;
}
// cLay varsion 20201018-1

// --- original code ---
// int N, X[20], Y[20], Z[20];
// ll dp[131072][17];
// {
//   rd(N,(X,Y,Z)(N));
//   rep(i,1<<N) rep(j,N) dp[i][j] = ll_inf;
//   dp[0][0] = 0;
//   rep(mask,1<<N) rep(i,N) if(dp[mask][i] < ll_inf) rep(j,N) if(!BIT_ith(mask,j)){
//     dp[mask|(1<<j)][j] <?= dp[mask][i] + abs(X[i]-X[j]) + abs(Y[i]-Y[j]) + max(Z[j]-Z[i], 0);
//   }
//   wt(dp[(1<<N)-1][0]);
// }


#include <bits/stdc++.h>
#define fi first
#define se second
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define rng(a) a.begin(),a.end()
#define rrng(a) a.rbegin(),a.rend()
#define isin(x,l,r) ((l) <= (x) && (x) < (r))
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
#define pcnt __builtin_popcountll
#define uni(x) x.erase(unique(rng(x)),x.end())
#define snuke srand((unsigned)clock()+(unsigned)time(NULL));
#define show(x) cerr<<#x<<" = "<<x<<endl;
#define PQ(T) priority_queue<T,v(T),greater<T> >
#define bn(x) ((1<<x)-1)
#define dup(x,y) (((x)+(y)-1)/(y))
#define newline puts("")
#define v(T) vector<T>
#define vv(T) v(v(T))
using namespace std;
typedef long long int ll;
typedef unsigned uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef tuple<int,int,int> T;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;
typedef vector<T> vt;
int getInt(){int x;scanf("%d",&x);return x;}
template<typename T>istream& operator>>(istream&i,v(T)&v){rep(j,sz(v))i>>v[j];return i;}
template<typename T>string join(const v(T)&v){stringstream s;rep(i,sz(v))s<<' '<<v[i];return s.str().substr(1);}
template<typename T>ostream& operator<<(ostream&o,const v(T)&v){if(sz(v))o<<join(v);return o;}
template<typename T1,typename T2>istream& operator>>(istream&i,pair<T1,T2>&v){return i>>v.fi>>v.se;}
template<typename T1,typename T2>ostream& operator<<(ostream&o,const pair<T1,T2>&v){return o<<v.fi<<","<<v.se;}
template<typename T>bool mins(T& x,const T&y){if(x>y){x=y;return true;}else return false;}
template<typename T>bool maxs(T& x,const T&y){if(x<y){x=y;return true;}else return false;}
template<typename T>ll suma(const v(T)&a){ll res(0);for(auto&&x:a)res+=x;return res;}
const double eps = 1e-10;
const ll LINF = 1001002003004005006ll;
const int INF = 1001001001;
#define dame { puts("-1"); return 0;}
#define yn {puts("Yes");}else{puts("No");}
const int MX = 200005;

// Unionfind
struct uf{
  vi d;
  uf() {};
  uf(int mx) : d(mx,-1) {};
  int root(int x){
    if(d[x]<0) return x;
    return d[x] = root(d[x]);
  }
  bool unite(int x, int y){
    x = root(x); y = root(y);
    if(x == y) return false;
    if(d[x] > d[y]) swap(x,y);
    d[x] += d[y]; d[y] = x;
    return true;
  }
  bool same(int x, int y) { return root(x) == root(y);}
  int size(int x){ return -d[root(x)];}
  int operator[] (int x) {return root(x);}
  int operator() (int x) {return size(x);}
};

int main() {
  int n, q; cin >> n >> q;
  vi c(n);
  rep(i,n) cin >> c[i], --c[i];

  vector<set<int> > s(n); // 1次元目が根の２次元目にその根がどのような種類のクラスを保持しているか
  vector<map<int,int> > m(n); // 1次元目が根の２次元目で各クラスに何人いるかを保持
  rep(i,n){
    s[i].insert(c[i]);
    m[i][c[i]] = 1;
  }

  uf dis(n);

  vi ans;
  rep(_,q){
    int qi; cin >> qi;
    if(qi == 1){
      int a,b; cin >> a >> b; --a,--b;
      if(dis.same(a,b)) continue;
      if(dis.size(a) < dis.size(b)) swap(a,b);
      int ra = dis.root(a), rb = dis.root(b);
      for(int clsb : s[rb]){
        if(s[ra].count(clsb)) m[ra][clsb] += m[rb][clsb];
        else s[ra].insert(clsb), m[ra][clsb] = m[rb][clsb];
      }
      // printf("ra: %d m[ra][1]: %d\n", ra, m[ra][1]);
      dis.unite(a,b);

    }else{
      int x,y; cin >> x >> y; --x,--y;
      ans.push_back(m[dis.root(x)][y]);
    }
  }
  for(int res: ans) cout << res << endl;
  return 0;
}

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;

#define rep(i,n) for (long long i = 0; i < (n); ++i)
#define DIV 1000000007 //10^9+7
#define INF LONG_MAX/3
#define bit(n) (1LL<<(n))

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

// 素集合データ構造
struct UnionFind
{
  // par[i]：データiが属する木の親の番号。i == par[i]のとき、データiは木の根ノードである
  vector<int> par;
  // sizes[i]：根ノードiの木に含まれるデータの数。iが根ノードでない場合は無意味な値となる
  vector<int> sizes;
  // group -> (class, num)
  map<ll, map<ll, ll> >class_sizes;

  UnionFind(int n) : par(n), sizes(n, 1) {
	  // 最初は全てのデータiがグループiに存在するものとして初期化
	  for(int i = 0; i < n; i++){
		  par[i] = i;
	  }
  }

  void set_class(ll num, ll cls) {
	  class_sizes[num][cls] = 1;
  }

  // データxが属する木の根を得る
  int find(int x) {
    if (x == par[x]) return x;
    return par[x] = find(par[x]);  // 根を張り替えながら再帰的に根ノードを探す
  }

  // 2つのデータx, yが属する木をマージする
  void unite(int x, int y) {
    // データの根ノードを得る
    x = find(x);
    y = find(y);

    // 既に同じ木に属しているならマージしない
    if (x == y) return;

    // xの木がyの木より大きくなるようにする
    if (sizes[x] < sizes[y]) swap(x, y);

    // xがyの親になるように連結する
    par[y] = x;
    sizes[x] += sizes[y];
    for(pair<ll, ll> item: class_sizes[y]) {
	    class_sizes[x][item.first] += item.second;
    }
    // sizes[y] = 0;  // sizes[y]は無意味な値となるので0を入れておいてもよい
  }

  // 2つのデータx, yが属する木が同じならtrueを返す
  bool same(int x, int y) {
    return find(x) == find(y);
  }

  // データxが含まれる木の大きさを返す
  int size(int x) {
    return sizes[find(x)];
  }
  ll size2(int x, int y) {
	  return class_sizes[find(x)][y];
  }
};

int main(){
	ll N, Q;
	cin >> N >> Q;
	vector<ll> C(N);
	rep(i, N) cin >> C[i];
	UnionFind uf(N+5);
	rep(i, N) uf.set_class(i, C[i]);

	rep(i, Q) {
		ll a, b, c;
		cin >> a >> b >> c;
		if(a == 1) {
			b--;c--;
			uf.unite(b, c);
		} else {
			b--;
			cout << uf.size2(b, c) << endl;
		}

	}

}


#include <bits/stdc++.h>

long long func(std::vector<std::pair<long long, long long>> &vw, std::vector<long long> &boxsize, int l, int r) {
  std::vector<long long> box;
  for (int i = 0; i < (int)boxsize.size(); ++i) {
    if (i < l || i > r) box.push_back(boxsize[i]);
  }

  std::vector<bool> used(box.size(), false);
  std::sort(box.begin(), box.end());

  long long res = 0LL;
  for (int i = 0; i < (int)vw.size(); ++i) {
    long long value = vw[i].first;
    long long weight = vw[i].second;

    int index = std::lower_bound(box.begin(), box.end(), weight) - box.begin();
    while (index < (int)box.size() && used[index]) ++index;
    if (index < (int)box.size()) { used[index] = true; res += value; }
  }

  return res;
}

int main() {
  int n, m, q;
  std::cin >> n >> m >> q;
  std::vector<std::pair<long long, long long>> vw(n);
  for (int i = 0; i < n; ++i) std::cin >> vw[i].second >> vw[i].first;
  std::vector<long long> boxsize(m);
  for (int i = 0; i < m; ++i) std::cin >> boxsize[i];

  std::sort(vw.begin(), vw.end(), std::greater<std::pair<long long, long long>>());

  std::vector<long long> res;
  for (int i = 0; i < q; ++i) {
    int l, r;
    std::cin >> l >> r;
    --l; --r;
    res.push_back(func(vw, boxsize, l, r));
  }

  for (long long ans : res) std::cout << ans << std::endl;
  return 0;
}

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

// @@ !! LIM()

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

  ll N, M; cin >> N >> M;
  using nbr_t = tuple<ll, ll, bool>;
  vector<vector<nbr_t>> nbr(N + 1);
  vector<bool> edir(M + 1);
  for (ll i = 1; i <= M; i++) {
    ll a, b; cin >> a >> b;
    nbr[a].emplace_back(b, i, true);
    nbr[b].emplace_back(a, i, false);
  }
  vector<ll> C(N + 1);
  for (ll i = 1; i <= N; i++) cin >> C[i];
  vector<bool> visited(N + 1);
  auto dfs = [&](auto rF, ll nd) -> void {
    if (visited[nd]) return;
    visited[nd] = 1;
    for (auto [m, ei, fl] : nbr[nd]) {
      if (C[nd] > C[m]) {
        edir[ei] = fl;
      }else if (C[nd] < C[m]) {
        edir[ei] = !fl;
      }else {
        edir[ei] = fl;
        rF(rF, m);
      }
    }
  };
  for (ll i = 1; i <= N; i++) {
    dfs(dfs, i);
  }

  for (ll i = 1; i <= M; i++) {
    if (edir[i]) {
      cout << "->\n";
    }else {
      cout << "<-\n";
    }
  }

  return 0;
}


#include<iostream>

using namespace std;

int main()

{

int a,b,c,d;

cin>>a>>b>>c>>d;

int result = b-c;

cout<<result <<endl;

return 0;

}

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

int main() {
    vector<ll> a(2);
    for (int i = 0; i < 2; i++) {
        std::cin >> a[i];
    }
    sort(a.begin(),a.end());

    if(a[0]+3>a[1]){
        std::cout << "Yes" << std::endl;
    }else{
        std::cout << "No" << std::endl;
    }
}