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

#define ll long long
#define MOD 1000000007
#define pii pair <ll, ll>

long long GCD(long long a, long long b)
{
    if (!b) return a;
    return GCD(b, a % b);
}

vector <int> graph[2001];
queue <int> q;
int n;
pii arr[200001];

int main()
{
    ll n, k;
    scanf("%lld %lld", &n, &k);
    for (int i = 0; i < n; i++)
    {
        scanf("%lld %lld", &arr[i].first, &arr[i].second);
    }
    sort(arr, arr + n);
    for (int i = 0; i < n; i++)
        if (k >= arr[i].first)
            k += arr[i].second;
    printf("%lld", k);
}

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

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
// You should only debug a pair of simple data types. For example,
// the debug won't work if one of pair's elements is collection type
// (std::vector, std::map, std::set...).
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

// Shortcuts for "common" data types in contests
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<char,char> pcc;
typedef pair<char,int> pci;
typedef pair<int,char> pic;
typedef vector<pii> vpii;
typedef set<int> si;
typedef set<ll> sll;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
#define ff first
#define ss second
#define endl '\n'
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define rep(i, a, b) for(int i = a; i < b; i++)
#define repv(c, it) \
for(auto it = (c).begin(); it != (c).end(); it++)
#define repm(c, it) \
for(mll::iterator it = (c).begin(); it != (c).end(); it++)
#define inf 1000000007
#define pb push_back
const long long mod = 1000000007;
const double pi = acos(-1);

int main() {
    //decreases the time taken by cin,cout.
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    //freopen("error.txt", "w", stderr);
    freopen("output.txt", "w", stdout);
    #endif

    ll n,k;cin>>n>>k;
    //ll c[n+1];c[0]=k;
    ll x,y;
    vector<vll> tt(n);
    rep(i,0,n)
    {
    	cin>>x>>y;
    	tt[i].push_back(x);
    	tt[i].push_back(y);

    }
    sort(all(tt));
    //rep(i,0,n){c[i+1]=c[i]+a[i][1];}

    ll ans=k,sum=k;
    rep(i,0,n)
    {
    	if(sum<tt[i][0]){ans=sum;break;}
    	else
    	{
    		sum+=tt[i][1];
    		ans=sum;
    	}
    }
    cout<<ans;

    return 0;

}


//#include <atcoder/maxflow.hpp>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>

#include <iostream>
#include <map>
#include <list>
#include <set>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <queue>
#include <deque>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iterator>
#include <random>
#include <chrono>
#include <complex>
#include <bitset>
#include <fstream>

#define forr(i,start,count) for (int i = (start); i < (start)+(count); ++i)
#define set_map_includes(set, elt) (set.find((elt)) != set.end())
#define readint(i) int i; cin >> i
#define readll(i) ll i; cin >> i
#define readdouble(i) double i; cin >> i
#define readstring(s) string s; cin >> s

typedef long long ll;

//using namespace __gnu_pbds;
//using namespace atcoder;
using namespace std;

//const ll modd = (1000LL * 1000LL * 1000LL + 7LL);
const ll modd = 998244353;

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

    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<int> rand_gen(0, modd);   // rand_gen(rng) gets the rand no

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

    cout.precision(12);

//    readint(test_cases);
    int test_cases = 1;
    forr(t, 1, test_cases) {
        readint(n); readint(m);
        struct info {
            int i;
            ll c,d;
        };
        vector<vector<info>> adj(n);
        forr(i,0,m) {
            readint(aa); --aa; readint(bb); --bb;
            readll(c); readll(d);
            if (aa!=bb) {
              adj[aa].push_back({bb,c,d});
              adj[bb].push_back({aa,c,d});
            }
        }
        vector<bool> visited(n, false);
        stack<int> todo; todo.push(0);
        while (!todo.empty()) {
            auto curr = todo.top(); todo.pop();
            if (visited[curr]) { continue; }
            visited[curr] = true;
            for(auto x : adj[curr]) {
                todo.push(x.i);
            }
        }
        if (!visited.back()) {
            cout << -1 << endl;
            continue;
        }

        priority_queue<pair<ll,int>> todoo; todoo.push(make_pair(0,0));
        vector<bool> visit(n, false);
        while (!todoo.empty()) {
            auto curr = todoo.top(); todoo.pop();
            if (visit[curr.second]) { continue; }
            visit[curr.second] = true;
            ll tim = -curr.first;
            if (curr.second==n-1) {
                cout << tim << endl;
                return 0;
            }
            for(auto x : adj[curr.second]) {
              vector<ll> candidates; candidates.push_back(0);
              ll p = (ll)sqrt(x.d) - 1-tim;
              candidates.push_back(p-2);
              candidates.push_back(p-1);
              candidates.push_back(p);
              candidates.push_back(p+1);
              candidates.push_back(p+2);
              for(ll w : candidates) {
                if (w>=0)  todoo.push(make_pair(-(tim + x.c + (x.d/(tim+1+w)) + w ), x.i));
              }

            }
        }

    }

    return 0;
}

#include <iostream>
#include <vector>
#include  <numeric>
#include<cstdlib>
#include <map>
#include <set>
#include <math.h>
#define ll long long
#define MAXN 100000
using namespace std;

std::vector<std::tuple<int,ll,ll>> edges[MAXN+2];
ll GetOptTime(ll d) {
    // t + d/(t+1) is minimized
    ll topt = (ll)sqrt(d);
    ll opt_time = -1;
    for(ll t=max(0ll,topt-20);t<=topt+20;t++) {
        ll curr_time = t+d/(t+1);
        if (opt_time == -1 || curr_time < opt_time) {
            topt = t;
            opt_time = curr_time;
        }
    }
    return topt;
}

bool done[MAXN+2];

int main() {
    int N,M;
    cin>>N>>M;
    for(int i=1;i<=M;i++) {
        int a,b;
        ll c,d;
        cin>>a>>b>>c>>d;
        edges[a].push_back(std::make_tuple(b,c,d));
        edges[b].push_back(std::make_tuple(a,c,d));
    }

    for(int u=1;u<=N;u++) {
        done[u]=false;
    }

    set<pair<ll,int>> Q;
    Q.insert({0,1});
    while(!Q.empty()) {
        auto it = Q.begin();
        int u = it->second;
        ll curr_time = it->first;
        Q.erase(it);
        if (done[u]) continue;
        if (u == N) {
            cout << curr_time << endl;
            return 0;
        }
        done[u]=true;
        for(auto vcd : edges[u]) {
            int v = std::get<0>(vcd);
            ll c = std::get<1>(vcd);
            ll d = std::get<2>(vcd);
            // t + c + d/(t+1) for t >= curr_time
            ll opt_time = max(curr_time, GetOptTime(d));
            Q.insert({opt_time+c+d/(opt_time+1),v});
        }
    }

    cout << -1 << endl;

}


#include <iostream>
#include <algorithm>
#include <vector>
typedef long long ll;
using namespace std;

template <class T> void input(T& a){
    cin>>a;
}

int main(){
  int A,B,C;
  input(A);
  input(B);
  input(C);
  if((A*A+B*B)<C*C){
    cout <<"Yes"<<endl;
  }
  else{
    cout <<"No"<<endl;
  }

  return 0;
}

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

#define fs(n) fixed << setprecision(n)
using ll = long long;
using ld = long double;

ll fact(ll x) { return x <= 1 ? 1 : x * fact(x - 1); }

//再帰処理で時間を食い過ぎるので階乗をメモ化する
map<ll, ll> factMemo;
ll memo_fact(ll x){
  if(factMemo[x] != 0) return factMemo[x];
  else return x <= 1 ? 1 : x * fact(x - 1);
}

int sign(int x){
  return (x > 0) - (x < 0);
}

bool isLeapYear(int y, int m){
  return (y % 400 == 0 || (y % 4 == 0 && y % 100)) && m == 2;
}

vector<int> AllDivs(int d){
	vector<int> resDivs(0);
	for(int i = 1; i < (int)sqrt(d); i++){
		if(d % i == 0){
			resDivs.push_back(i);
			resDivs.push_back(d / i);
		}
	}
	sort(resDivs.begin(), resDivs.end());
	return resDivs;
}

bool IsPrime(int num){
	bool ans = true;
	if(num < 2) return false;
	else if (num == 2) return true;
	else{
		for(int i = 2; i <= (int)sqrt(num); i++){
			if(num % i == 0){
					ans = false;
			}
		}
	}
	return ans;
}

int NextPrime(int d){
	int ans = d;
	while(true){
		ans++;
		if(IsPrime(ans)) break;
	}
	return ans;
}

vector<int> Dec2Bin(int x, int len){
	vector<int> res(len, 0);
	int d = 1, pt = len - 1;
	while(d <= x){
		res[pt] = (x & d ? 1 : 0);
		d *= 2; pt--;
	}
	return res;
}

int avg(int a, int b){
  return (a + b) / 2;
}

ll permu(ll m, ll c){
  ll ans = 1;
  for(ll i = c; i <= m; i++){
    ans *= i;
  }
  return ans;
}

ll combi(ll m, ll c){
  ll mf = memo_fact(c);
  factMemo[c] = mf;
  return (permu(m, c) / mf);
}

ll choose_two(ll m){
  return m * (m + 1) / 2;
}

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

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

int main(){
  // 反転はフラグで先頭と末尾を切り替え
  string s; cin >> s;
  bool flg = true;
  string t = "";
  for(int i = 0; i < s.length(); i++){
    string u = s.substr(i, 1);
    if(u != "R"){
      if(t.length() == 0){
        t += u;
        continue;
      }
      if(flg){
        // 削除する
        if(t.substr(t.length() - 1, 1) == u){
          t.erase(t.length() - 1);
        }else t += u;
      }else{
        if(t.substr(0, 1) == u){
          t.erase(0, 1);
        }else t = u + t;
      }
    }else flg = !flg;
    // cout << t << endl;
  }
  if(!flg) reverse(t.begin(), t.end());
  cout << t << endl;
}


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

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

vector<string> vec_splitter(string s) {
	s += ',';
	vector<string> res;
	while(!s.empty()) {
		res.push_back(s.substr(0, s.find(',')));
		s = s.substr(s.find(',') + 1);
	}
	return res;
}

void debug_out(
vector<string> __attribute__ ((unused)) args,
__attribute__ ((unused)) int idx,
__attribute__ ((unused)) int LINE_NUM) { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
	if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
	stringstream ss; ss << H;
	cerr << args[idx] << " = " << ss.str();
	debug_out(args, idx + 1, LINE_NUM, T...);
}

#ifdef LOCAL
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
#else
#define debug(...) 42
#endif

double get_time() {
	return 1.0 * clock() / CLOCKS_PER_SEC;
}

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());  // returns unsigned ints!

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

	vector<int> A(K);
	for(int i = 0; i < K; i++)
		cin >> A[i];

	vector<long long> B(K);

	auto can = [&] (long long tar) {
		// |N * B_i - M * A_i| <= tar
		vector<long long> low(K), high(K);
		for(int i = 0; i < K; i++) {
			low[i] = ((long long) M * A[i] - tar);
			if(low[i] < 0) {
				low[i] = 0;
			}
			else
				low[i] = (low[i] + N - 1) / N;

			high[i] = ((long long) M * A[i] + tar) / N;

			while(low[i] > 0 && abs((long long) N * (low[i] - 1) - (long long) M * A[i]) <= tar)
					low[i]--;
				while(abs((long long) N * (high[i] + 1) - (long long) M * A[i]) <= tar)
					high[i]++;

			if(low[i] <= high[i]) {
				while(low[i] > 0 && abs((long long) N * (low[i] - 1) - (long long) M * A[i]) <= tar)
					low[i]--;
				while(abs((long long) N * (high[i] + 1) - (long long) M * A[i]) <= tar)
					high[i]++;
				if(low[i] > high[i])
					return false;
				assert(abs((long long) N * low[i] - (long long) M * A[i]) <= tar);
				assert(abs((long long) N * high[i] - (long long) M * A[i]) <= tar);
			}
		}

		long long have = M;
		for(int i = 0; i < K; i++) {

			B[i] = low[i];
			have -= low[i];
		}

		if(have < 0)
			return false;

		for(int i = 0; i < K; i++) {
			long long can = high[i] - low[i];
			B[i] += min(can, have);
			have -= min(can, have);
		}

		if(have > 0)
			return false;

		return true;
	};

	long long lo = 0, hi = 1E18 + 5;
	while(lo < hi) {
		long long mid = (lo + hi) / 2;
		if(can(mid))
			hi = mid;
		else
			lo = mid + 1;
	}

	assert(can(lo));

	for(int i = 0; i < K; i++)
		cout << B[i] << ' ';
	cout << '\n';
}

#include<bits/stdc++.h>
template <typename _Tp>void read(_Tp &x){
	char ch(getchar());bool f(false);while(!isdigit(ch))f|=ch==45,ch=getchar();
	x=ch&15,ch=getchar();while(isdigit(ch))x=x*10+(ch&15),ch=getchar();
	if(f)x=-x;
}
template <typename _Tp,typename... Args>void read(_Tp &t,Args &...args){read(t);read(args...);}
const int N=105,mod=1000000007,inv2=(mod+1)/2;
typedef long long ll;
template<typename _Tp1,typename _Tp2>inline void add(_Tp1 &a,_Tp2 b){(a+=b)>=mod&&(a-=mod);}
template<typename _Tp1,typename _Tp2>inline void sub(_Tp1 &a,_Tp2 b){(a-=b)<0&&(a+=mod);}
ll ksm(ll a,ll b=mod-2){ll res=1;while(b){if(b&1)res=res*a%mod;a=a*a%mod,b>>=1;}return res;}
int a[N],b[N];
int X[N*N],Y[N*N],n;
struct mat{
	int a[N][N];
	mat operator * (const mat &o)const{
		mat c;memset(c.a,0,sizeof(c.a));
		for(int i=0;i<n;++i)for(int k=0;k<n;++k)for(int j=0;j<n;++j)add(c.a[i][j],1ULL*a[i][k]*o.a[k][j]%mod);
		return c;
	}
}I,M,orig;
mat ksm(mat a,int b){
	mat res=I;
	while(b){
		if(b&1)res=res*a;
		a=a*a,b>>=1;
	}
	return res;
}
int main(){
	int m,k;read(n,m,k);
	for(int i=0;i<n;++i)I.a[i][i]=1;
	for(int i=0;i<n;++i)read(orig.a[i][0]);
	for(int i=1;i<=m;++i)read(X[i],Y[i]);
	ll inv=ksm(m);
	for(int i=0;i<n;++i)M.a[i][i]=1;
	for(int i=1;i<=m;++i){
		int x=X[i]-1,y=Y[i]-1;
		add(M.a[x][x],1LL*inv*(mod-inv2)%mod),add(M.a[x][y],1LL*inv*inv2%mod);
		add(M.a[y][y],1LL*inv*(mod-inv2)%mod),add(M.a[y][x],1LL*inv*inv2%mod);
	}
	mat o=ksm(M,k)*orig;
	for(int i=0;i<n;++i)printf("%d\n",o.a[i][0]);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
long long INF = 1LL^60;
using ll = long long;
using vll = vector<ll>;
using mll = map<ll, ll>;

void solve(long long N, long long A, long long B){
    cout << N - A + B<< endl;
}

int main(){
    long long N;
    scanf("%lld",&N);
    long long A;
    scanf("%lld",&A);
    long long B;
    scanf("%lld",&B);
    solve(N, A, B);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int A,B,C;
  cin >> A >> B >> C;
  if(A > B ){
    cout << "Takahashi" << endl;
  }
  else if(A == B && C == 1){
    cout << "Takahashi" << endl;
  }
  else{
    cout << "Aoki" << endl;
  }
  return 0;
}


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

int main()
{
    int n; cin >> n;
    vector<pair<int, int>> z;
    pair<int, int> c;
    for (int i=0; i<n; i++)
    {
        cin >> c.first >> c.second;
        z.push_back(c);
    }
    bool flag = false;
    for (int i1=0; i1<n; i1++)
    {
        for (int i2=i1+1; i2<n; i2++)
        {
            for (int i3=i2+1; i3<n; i3++)
            {
                int p = (z[i1].first - z[i2].first) * (z[i1].second - z[i3].second);
                int q = (z[i1].first - z[i3].first) * (z[i1].second - z[i2].second);
                if (p == q)
                {
                    flag = true;
                    break;
                }
            }
            if (flag) break;
        }
        if (flag) break;
    }
    if (flag) cout << "Yes" << endl;
    else cout << "No" << endl;
}

#include <bits/stdc++.h>
// #include <atcoder/all>
// using namespace atcoder;
#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)
#define rep2(i, s, n) for (ll i = s; i < (ll)(n); i++)
#define repr(i, n) for (ll i = n; i >= 0; i--)
#define pb push_back
#define COUT(x) cout << (x) << "\n"
#define COUTF(x) cout << setprecision(15) << (x) << "\n"
#define ENDL cout << "\n"
#define DF(x) x.erase(x.begin())
#define ALL(x) x.begin(), x.end()
#define SORT(x) sort(ALL(x))
#define RSORT(x) sort(x.rbegin(), x.rend())
#define REVERSE(x) reverse(ALL(x))
#define MAX(x) *max_element(ALL(x))
#define MAXI(x) max_element(ALL(x)) - x.begin()
#define SUM(x) accumulate(ALL(x), 0ll)
#define COUNT(x, y) count(ALL(x), y);
#define ANS cout << ans << "\n"
#define YES cout << "YES\n";
#define NO cout << "NO\n";
#define Yes cout << "Yes\n";
#define No cout << "No\n";
#define init() \
  cin.tie(0);  \
  ios::sync_with_stdio(false)
#define LINE cerr << "[debug] line: " << __LINE__ << endl;
#define debug(x) cerr << "[debug] " << #x << ": " << x << endl;
#define debugV(v)                       \
  cerr << "[debugV] " << #v << ":";     \
  rep(z, v.size()) cerr << " " << v[z]; \
  cerr << endl;
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using mll = map<ll, ll>;
using qll = queue<ll>;
using P = pair<ll, ll>;
using vp = vector<P>;
using vs = vector<string>;

template <typename T>
inline istream& operator>>(istream& i, vector<T>& v) {
  rep(j, v.size()) i >> v[j];
  return i;
}

template <typename T1, typename T2>
inline istream& operator>>(istream& i, pair<T1, T2>& v) {
  return i >> v.first >> v.second;
}

constexpr ll INF = 0x3f3f3f3f3f3f3f3f;
constexpr ld PI = 3.141592653589793238462643383279;
ll get_digit(ll x) {
  return to_string(x).size();
}

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

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

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

signed main() {
  init();
  ll N;
  cin >> N;
  vp A(N);
  cin >> A;

  rep(i, N) {
    rep(j, N) {
      rep(k, N) {
        if (i == j) continue;
        if (j == k) continue;
        if (i == k) continue;
        ll a = A[j].first - A[i].first;
        ll b = A[j].second - A[i].second;
        ll c = A[k].first - A[i].first;
        ll d = A[k].second - A[i].second;
        if (b * c == a * d) {
          Yes;
          return 0;
        }
      }
    }
  }
  No;
  return 0;
}


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

using namespace std;

struct mountain
{
  string name;
  int height;
};

int main()
{
  int n;
  string input, most, second;
  long input_height, most_height, second_height;
  most_height = 0;
  second_height = 0;

  cin >> n;

  for (int i = 0; i < n; i++)
  {
    cin >> input >> input_height;
    if (i == 0)
    {
      most = input;
      most_height = input_height;
    }
    else if (most_height < input_height)
    {
      second = most;
      second_height = most_height;
      most = input;
      most_height = input_height;
    }
    else
    {
      if (second_height < input_height)
      {
        second = input;
        second_height = input_height;
      }
    }
  }
  cout << second << endl;

  return 0;
}

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
#define FAST ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define mp make_pair
#define pb push_back
#define inF freopen("input.txt", "r", stdin);
#define outF freopen("output.txt", "w", stdout);
#define endl '\n'
#define MOD 1000000007
#define mm(arr) memset(arr, 0, sizeof(arr))
#define F first
#define S second
#define scanArray(a,n) for(int i = 0; i < n; i++){cin >> a[i];}
#define coutArray(a,n) for(int i = 0; i < n; i++){cout << a[i] << " ";}cout << endl;
#define ld long double
#define PI 3.141592653589793238
#define all(v) v.begin(), v.end()
#define sz(x) (int)(x.size())
#define int ll

void solve(){
    int n; cin >> n;
    vector<pair<int, string>> v(n);
    for(int i = 0; i < n; i++){
        cin >> v[i].second >> v[i].first;
    }
    sort(all(v));
    cout << v[n - 2].second << endl;
}

int32_t main(){
    FAST
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
#define pi 3.141592653589793238
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#define MOD 1000000007
#define INF 999999999999999999
#define pb push_back
#define ff first
#define ss second

#define mt make_tuple
#define ll long long
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

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

bool find_any_solution(ll a, ll b, ll c, ll &x0, ll &y0, ll &g) {
    g = gcd(abs(a), abs(b), x0, y0);
    if (c % g) {
        return false;
    }

    x0 *= c / g;
    y0 *= c / g;
    if (a < 0) x0 = -x0;
    if (b < 0) y0 = -y0;
    return true;
}

typedef tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main() {
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    fast;
    ll T;
    cin>>T;

    while(T--)
    {
        ll n,s,k;
        cin>>n>>s>>k;
        ll val=n-s;

        ll g=__gcd(n,k);

        if(val%g!=0)
        {
            cout<<-1<<endl;
            continue;
        }

        ll pass=0;
        ll x0,y0;
        int vothing=find_any_solution(k,-n,val,x0,y0,pass);

        ll front=n/pass;

        if(x0<0)
        {
            ll c=-x0;
            ll to=c/front;
            to++;
            x0+=front*to;
        }

        if(x0>0)
        {
            ll to=x0/front;
            x0-=front*to;
        }

        cout<<x0<<endl;
    }
    return 0;
}

#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
template<class S, class T> inline S min_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(int x){
  int s=0;
  int m=0;
  char f[10];
  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');
  }
}
int X;
int Y;
int A[10000];
int main(){
  rd(X);
  rd(Y);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=(0);Lj4PdHRW<(X*Y);Lj4PdHRW++){
      rd(A[Lj4PdHRW]);
    }
  }
  X *= Y;
  {
    int e98WHCEY;
    int cTE1_r3A;
    if(X==0){
      cTE1_r3A = 0;
    }
    else{
      cTE1_r3A = A[0];
      for(e98WHCEY=(1);e98WHCEY<(X);e98WHCEY++){
        cTE1_r3A = min_L(cTE1_r3A, A[e98WHCEY]);
      }
    }
    {
      int xr20shxY;
      int WYIGIcGE;
      if(X==0){
        WYIGIcGE = 0;
      }
      else{
        WYIGIcGE = A[0];
        for(xr20shxY=(1);xr20shxY<(X);xr20shxY++){
          WYIGIcGE += A[xr20shxY];
        }
      }
      wt_L(WYIGIcGE- X *cTE1_r3A);
      wt_L('\n');
    }
  }
  return 0;
}
// cLay version 20201206-1

// --- original code ---
// int X, Y, A[1d4];
// {
//   rd(X,Y,A(X*Y));
//   X *= Y;
//   wt(sum(A(X)) - X * min(A(X)));
// }


/*
    author : aryan57
    created : 06-June-2021 18:04:35 IST
*/
#include <bits/stdc++.h>
using namespace std;

template <typename A, typename B>
ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template <typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type>
ostream &operator<<(ostream &os, const T_container &v)
{
    os << '{';
    string sep;
    for (const T &x : v)
        os << sep << x, sep = ", ";
    return os << '}';
}
void dbg_out() { cerr << endl; }
template <typename Head, typename... Tail>
void dbg_out(Head H, Tail... T)
{
    cerr << ' ' << H;
    dbg_out(T...);
}
#ifndef ONLINE_JUDGE
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif

#define int long long
#define X first
#define Y second
#define pb push_back
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(), (a).end()
#define F(i, a, b) for (int i = a; i <= b; i++)
#define RF(i, a, b) for (int i = a; i >= b; i--)

const int mxn = 1e5;
const long long INF = 1e16;
const int32_t M = 1000000007;
// const int32_t M = 998244353;
const long double pie = acos(-1);

struct Edge
{
    int u, v, d, c;
};

void solve_LOG()
{
    int n, m;
    cin >> n >> m;

    vector<Edge> adj[n + 1];

    F(i, 1, m)
    {
        Edge e;
        cin >> e.u >> e.v >> e.c >> e.d;
        // if(e.u==e.v)continue;
        adj[e.u].push_back(e);
        adj[e.v].push_back(e);
    }

    vector<int> mn(n + 1, INF);

    mn[1] = 0;

    using pii = pair<int, int>;
    priority_queue<pii, vector<pii>, greater<pii>> q;
    q.push({0, 1});
    while (!q.empty())
    {
        int v = q.top().second;
        int mn_v = q.top().first;
        q.pop();
        if (mn_v != mn[v])
            continue;

        for (auto edge : adj[v])
        {
            int c=edge.c;
            int d=edge.d;

            int to=-1;
            if(edge.u==v)to=edge.v;
            else to=edge.u;

            int temp=INF;

            int dd=(int)sqrt(d);

            F(t,max(0ll,dd-(mn[v]+1)-5),max(0ll,dd-(mn[v]+1)+5))
            {
                temp=min(temp,mn[v]+t+c+d/(mn[v]+t+1));
            }

            if (temp < mn[to])
            {
                mn[to] = temp;
                q.push({mn[to], to});
            }
        }
    }

    if (mn[n] == INF)
    {
        cout << "-1\n";
        return;
    }

    cout << mn[n];
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
#ifdef ARYAN_SIEVE
    sieve();
#endif
#ifdef ARYAN_SEG_SIEVE
    segmented_sieve();
#endif
#ifdef ARYAN_FACT
    fact_init();
#endif
    // cout<<fixed<<setprecision(10);
    int _t = 1;
    // cin>>_t;
    for (int i = 1; i <= _t; i++)
    {
        // cout<<"Case #"<<i<<": ";
        solve_LOG();
    }
    return 0;
}
//	parsed : 06-June-2021 18:04:32 IST

//This Code was made by Chinese_zjc_.
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <set>
#include <time.h>
// #include<windows.h>
#define int long long
#define double long double
const double PI = acos(-1);
const double eps = 0.0000000001;
const int INF = 0x3fffffffffffffff;
int n, m, dis[100005], a[100005], b[100005], c[100005], d[100005], e[100005];
std::vector<int> to[100005];
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> que;
signed main()
{
    std::ios::sync_with_stdio(false);
    std::cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        std::cin >> a[i] >> b[i] >> c[i] >> d[i];
        to[a[i]].push_back(i);
        to[b[i]].push_back(i);
        e[i] = sqrt(d[i]);
    }
    std::fill(dis + 1, dis + 1 + n, INF);
    que.push({dis[1] = 0, 1});
    while (!que.empty())
    {
        int now = que.top().second;
        if (dis[now] != que.top().first)
        {
            que.pop();
            continue;
        }
        que.pop();
        for (auto i : to[now])
        {
            int nxt = a[i] ^ b[i] ^ now;
            for (int j = std::max(e[i] - 2, dis[now]), lim = j + 5; j <= lim; ++j)
            {
                if (dis[nxt] > c[i] + d[i] / (j + 1) + j)
                {
                    dis[nxt] = c[i] + d[i] / (j + 1) + j;
                    que.push({dis[nxt], nxt});
                }
            }
        }
    }
    std::cout << (dis[n] >= INF ? -1 : dis[n]) << std::endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
double k;
double a,b,c,d,s,p;
double f(double x)
{
	return -b/k+a;
}
int main()
{

    cin>>a>>b>>c>>d;
    b=-b;
    k=(b-d)/(a-c);
    s=f(0);
    printf("%.10lf",s);
	return 0;

}

#include<bits/stdc++.h>
#define loop(i, n) for(int i = 0; i < n; i++)
#define pb          push_back
#define ll          long long int
#define vi          vector<int>
#define pi          pair<int, int>
#define W(t)        int t; cin >> t; while(t--)
#define FIO         ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ff          first
#define ss          second
#define rep(i, a, b)for(ll i = a; i <= b; i++)
#define dep(i, a, b)for(ll i = a; i >= b; i--)
#define all(x)      x.begin(), x.end()
#define tr(it, a) for(auto it = a.begin(); it != a.end(); it++)
#define PI                3.14159265
using namespace std;
const ll mod = (ll)(998244353);
vector<ll> read(int n){

    vector<ll> v(n);

    loop(i, n)
        cin >> v[i];
    return v;
}
vector<ll> fact, invf;
ll powmod(ll a, ll b) {
    ll res = 1;
    a %= mod;
    for (; b; b >>= 1) {
        if (b & 1)
            res = res * a % mod;
        a = a * a % mod;
    }
    return res;
}

void build(int n) {
    fact = vector<ll>(n+1, 1);
    invf = vector<ll>(n+1, 1);
    for (int i = 2; i <= n; i++)
        fact[i] = fact[i-1] * i % mod;
    invf[n] = powmod(fact[n], mod-2);
    for (int i = n-1; i >= 2; i--)
        invf[i] = invf[i+1] * (i+1) % mod;
}

ll nChoosek(int n, int k) {
    if (n < k)
        return 0;
    return fact[n] * invf[k] % mod * invf[n-k] % mod;
}
ll test = 0;
void solve(){
    ll i, j, k, m, n, cnt = 0, ans = 0, sum = 0;

   double sx, sy, gx, gy;

   cin >> sx >> sy >> gx >> gy;

   double res = (gy*sx + gx*sy)/(sy+gy);

   cout <<fixed << setprecision(10) << res << "\n";

    test++;
}

int main(){
    FIO

    #ifndef ONLINE_JUDGE
	freopen("C:/Codeforces/input.txt", "r", stdin);
	freopen("C:/Codeforces/output.txt", "w", stdout);
	#endif
    ll i = 1;
    //W(t)
    solve();

    return 0;
}


#include "bits/stdc++.h"
//#include "atcoder/all"
using namespace std;
//using namespace atcoder;
//using mint = modint1000000007;
//const int mod = 1000000007;
//using mint = modint998244353;
//const int mod = 998244353;
//const int INF = 1e9;
//const long long LINF = 1e18;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep2(i,l,r)for(int i=(l);i<(r);++i)
#define rrep(i, n) for (int i = (n-1); i >= 0; --i)
#define rrep2(i,l,r)for(int i=(r-1);i>=(l);--i)
#define all(x) (x).begin(),(x).end()
#define allR(x) (x).rbegin(),(x).rend()
#define endl "\n"

long long gcd(long long a, long long b) {
	if (b == 0) return a;
	else return gcd(b, a%b);
}
long long lcm(long long x, long long y) {
	return x * y / gcd(x, y);
}
unordered_map<int, int>mp;
//約数列挙
void calc(int N) {
	for (int i = 1; i <= sqrt(N); i++) {
		if (0 == N % i) {
			mp[i] = gcd(mp[i], N);
			if (N != i * i) {
				mp[N / i] = gcd(mp[N / i], N);
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int N;
	cin >> N;
	vector<int>A(N);
	rep(i, N) {
		cin >> A[i];
	}
	int minA = 1e9;
	rep(i, N) {
		minA = min(minA, A[i]);
	}
	rep(i, N) {
		calc(A[i]);
	}
	int ans = 0;
	for (auto p : mp) {
		if ((p.first <= minA) && (p.first == p.second)) {
			ans++;
		}
	}
	cout << ans << endl;
	return 0;
}

#include "bits/stdc++.h"
#define rep(i,b) for(ll i=0;i<b;i++)
#define ll long long
using namespace std;
/*--Input//////////////////////////////////////////////////*/
inline void IN(void){return;}
template <typename First, typename... Rest>
void IN(First& first, Rest&... rest){
    cin >> first;
    IN(rest...);
    return;
}
#define SS(T, ...)      T __VA_ARGS__; IN(__VA_ARGS__);
#define SV(type,c,n) vector<type> c(n);for(auto& i:c)cin >> i;
/*--Output/////////////////////////////////////////////////*/
#define Yes(n) cout << ((n) ? "Yes" : "No"  ) << endl
#define First(n) cout << ((n) ? "First" : "Second"  ) << endl
inline int p(void){cout << endl; return 0;}
template<class Head> int p(Head&& head){cout << head;p();return 0;} template<class Head,class... Tail> int p(Head&& head,Tail&&... tail){cout<<head<<" ";p(forward<Tail>(tail)...);return 0;}
struct ProconInit {
    static constexpr int IOS_PREC = 15;
    static constexpr bool AUTOFLUSH = false;

    ProconInit() {
        cin.tie(nullptr);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(IOS_PREC);
        if(AUTOFLUSH)
            cout << unitbuf;
    }
} PROCON_INIT;

#define vl vector<ll>
#define debug(x) cerr<<#x<<" "<<x<<'\n';
#define all(x) (x).begin(),(x).end()
ll GCD(ll a, ll b) {
  if(a < b) return GCD(b, a);
  if(b==0){
      return a;
  }else{
      return GCD(b,a%b);
  }
}
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; }
bool cmp(pair<ll,ll> a, pair<ll,ll> b) { return a.second < b.second; }
ll MOD=1e9+7;

struct UnionFind {
    vector<int> par;

    UnionFind(int n) : par(n,-1) { }
    void init(int n) { par.assign(n, -1); }

    int root(int x) {
        if (par[x] < 0) return x;
        else return par[x] = root(par[x]);
    }

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

    bool unite(int x, int y) {
        x = root(x); y = root(y);
        if (x == y) return false;
        if (par[x] > par[y]) swap(x, y); // merge technique
        par[x] += par[y];
        par[y] = x;
        return true;
    }

    int size(int x) {
        return -par[root(x)];
    }
};
int main(){
    bool ok=true;

    SS(int,N,M);
    vector<vl> path(N);
    UnionFind uf(N);
    SV(ll,a,N);
    SV(ll,b,N);
    rep(i,M){
        SS(int,c,d);
        c--;d--;
        uf.unite(c,d);
    }
    rep(i,N){
        path.at(uf.root(i)).push_back(i);
    }
    rep(i,N){
        ll a_sum=0;
        ll b_sum=0;
        //debug(path.at(i).size());
        int t=path.at(i).size();
        rep(j,t){
            int po=path.at(i).back();
            path.at(i).pop_back();
            a_sum+=a[po];
            b_sum+=b[po];
        }
        if(a_sum!=b_sum)ok=false;
    }
    Yes(ok);
}


#include <bits/stdc++.h>
#define sz(v)   ((int)(v).size())
#define  all(v)    ((v).begin()),((v).end())
#define  allr(v)    ((v).rbegin()),((v).rend())
#define   pb         push_back
#define   mp         make_pair
#define   Y            imag()
#define   X            real()
#define    clr(v,d)      memset( v, d ,sizeof(v))
#define   angle(n)      atan2((n.imag()),(n.real()))
#define   vec(a,b)       ((b)-(a))
#define   length(a)      hypot( (a.imag()),(a.real()) )
#define   normalize(a)      (a)/(length(a))
#define    dp(a,b)          (((conj(a))*(b)).real())
#define    cp(a,b)          (((conj(a))*(b)).imag())
#define    lengthsqrt(a)       dp(a,a)
#define    rotate0( a,ang)    ((a)*exp( point(0,ang) ))
#define    rotateA(about,p,ang)   (rotate0(vec(about,p),ang)+about)
#define    lcm(a,b)                ((a*b)/(__gcd(a,b)))
#define    reflection0(m,v)         (conj((v)/(m))*(m))
#define     reflectionA(m,v,p0)     (conj( (vec(p0,v))/(vec(p0,m)) ) * (vec(p0,m)) ) + p0
#define     same(p1,p2)               ( dp(  vec(p1,p2),vec(p1,p2)) < eps )
#define     point                    complex<long double>
#define     PI                       acos(-1)
typedef  long long     ll ;
typedef  unsigned long long ull;
const double eps= (1e-15);
using namespace std;
int dcmp(double a,double b){   return fabs(a-b)<=eps ? 0: (a>b)? 1:-1  ;}
int getBit(ll num, int idx) {return ((num >> idx) & 1ll) == 1;}
int setBit1(int num, int idx) {return num | (1<<idx);}
ll setBit0(ll num, int idx) {return num & ~(1ll<<idx);}
ll flipBit(ll num, int idx) {return num ^ (1ll<<idx);}
void GO(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);}
int countNumBit1(int mask) {int ret=0; while (mask) 	{mask &= (mask-1);++ret;	}return ret;}
const ll N=1000+9,mod=998244353,sh=1000000,inf=1000000;
int n,m,a[N],b[N],mem[N][N][6];
int solve(int id1,int id2,int fl){

    if(id1>=n&&id2>=m){
        if(fl==1){
            return 0;
        }
        return inf;
    }
    if(id1>=n){
        if(fl==1) return (m-id2);
        return inf;
    }
    if(id2>=m){
        if(fl==1) return (n-id1);
        return inf;
    }

    int &ret=mem[id1][id2][fl];
    if(ret!=-1) return ret;
    int ans=inf;

    if(fl==2){
    if(id1<n&&id2<m)
    ans=min(ans,(a[id1]!=b[id2])+solve(id1+1,id2+1,1));
    if(id1<n&&id2+1<m)
    ans=min(ans,1+solve(id1,id2+1,3));
    if(id2<m&&id1+1<n)
    ans=min(ans,1+solve(id1+1,id2,4));
    }
    else if(fl==1){
        if(id1<n&&id2<m)
        ans=min(ans,(a[id1]!=b[id2])+solve(id1+1,id2+1,1));
        if(id1<n&&id2+1<m)
        ans=min(ans,1+solve(id1,id2+1,3));
        if(id2<m&&id1+1<n)
        ans=min(ans,1+solve(id1+1,id2,4));
    }
    else if(fl==3){
        if(id1<n&&id2<m)
        ans=min(ans,(a[id1]!=b[id2])+solve(id1+1,id2+1,1));
        if(id1<n&&id2+1<m)
        ans=min(ans,1+solve(id1,id2+1,3));
    }
    else if(fl==4){
        if(id1<n&&id2<m)
        ans=min(ans,(a[id1]!=b[id2])+solve(id1+1,id2+1,1));
        if(id2<m&&id1+1<n)
        ans=min(ans,1+solve(id1+1,id2,4));

    }
 return ret=ans;

}
int main(){
    GO();

    int T=1;
    //cin>>T;
    while(T--){
        cin>>n>>m;
        for(int i=0;i<n;i++) cin>>a[i];
        for(int i=0;i<m;i++) cin>>b[i];
        clr(mem,-1);

        cout<<solve(0,0,2)<<"\n";

    }

}

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

typedef tree<int, null_type, less<int>, rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set;
#define pf                  printf
#define sf(a)               scanf("%d",&a)
#define sfl(a)              scanf("%lld",&a)
#define sff(a,b)            scanf("%d %d",&a,&b)
#define sffl(a,b)           scanf("%lld %lld",&a,&b)
#define sfff(a,b,c)         scanf("%d %d %d",&a,&b,&c)
#define sfffl(a,b,c)        scanf("%lld %lld %lld",&a,&b,&c)
#define sffff(a,b,c,d)      scanf("%d %d %d %d",&a,&b,&c,&d)
#define sffffl(a,b,c,d)     scanf("%lld %lld %lld %lld",&a,&b,&c,&d)
#define sfffff(a,b,c,d,e)   scanf("%d %d %d %d %d",&a,&b,&c,&d,&e)
#define sfffffl(a,b,c,d,e)  scanf("%lld %lld %lld %lld %lld",&a,&b,&c,&d,&e)
#define sfc(a)              scanf("%c",&a)
#define pii                 pair<int,int>
#define ms(a,b)             memset(a,b,sizeof(a))
#define pb(a)               push_back(a)
#define pbp(a,b)            push_back({a,b})
#define db                  double
#define ft                  float
#define ll                  long long
#define ull                 unsigned long long
#define pii                 pair<int,int>
#define ff                  first
#define ss                  second
#define sz(x)               x.size()
#define all(x)              x.begin(),x.end()
#define CIN                 ios_base::sync_with_stdio(0); cin.tie(0)
#define max3(a, b, c)       max(a, b) > max(b, c) ? max(a, b) : max(b, c)
#define min3(a, b, c)       min(a, b) < min(b, c) ? min(a, b) : min(b, c)
#define for0(i,n)           for(int i=0;i<n;i++)
#define for1(i,n)           for(int i=1;i<=n;i++)
#define forrev(i,n)         for(int i=n-1; i>=0; i--)
#define forab(i,a,b)        for(int i=a;i<=b;i++)
#define forba(i,b,a)        for(int i=b;i>=a;i--)
#define stlloop(x)          for(__typeof(x.begin()) it=x.begin();it!=x.end();it++)
#define gcd(a, b)           __gcd(a, b)
#define lcm(a, b)           ((a)*((b)/gcd(a,b)))
#define case1(z)            cout<<"Case "<<z<<": "
#define case2(z)            printf("Case %d: ",z)
#define PI                  acos(-1) //3.14159265358979323846264338328
#define valid(tx,ty)        tx>=0 && tx<row && ty>=0 && ty<col
#define intlim              2147483648
#define N                   300005
#define inf                 100000008
#define mod                 1000000007

/*------------------------------Graph Moves----------------------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};   // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};  // Kings Move
//const int fx[]={-2, -2, -1, -1,  1,  1,  2,  2};  // Knights Move
//const int fy[]={-1,  1, -2,  2, -2,  2, -1,  1}; // Knights Move
/*---------------------------------------------------------------------*/

ll a[1003],b[1003];
ll dp[1003][1003];

int main()
{
    ll n,m,i,j;
    cin>>n>>m;
    for1(i,n)cin>>a[i];
    for1(i,m)cin>>b[i];
    for0(i,n+1)for0(j,m+1)dp[i][j] = max(i,j);

    for1(i,n)
    {
        for1(j,m)
        {
            if(a[i]==b[j])
            {
                dp[i][j] = min3(dp[i][j],dp[i-1][j-1],min(dp[i-1][j]+1,dp[i][j-1]+1));
            }
            else
            {
                dp[i][j] = min3(dp[i][j],dp[i-1][j-1]+1,min(dp[i-1][j]+1,dp[i][j-1]+1));
            }
        }
    }
    cout<<dp[n][m]<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define input(v) for (auto &i : v) cin >> i;
#define print(v) for (auto &j : v) cout << j << " "; cout << "\n";

void solve()
{
    int n;
    cin>>n;
    vector<int>a(n),b(n);input(a);input(b);
    int mx = max(a[0],b[0]);
    int mn = min(a[0],b[0]);
    for(int i=0;i<n;i++)
    {
        mx=min(mx,max(a[i],b[i]));
        mn=max(mn,min(a[i],b[i]));
    }
    if(mx-mn+1<0)
    {
        cout<<"0\n";
        return;
    }
    cout<<mx-mn+1<<"\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    int testcases=1;
    //cin>>testcases;
    while(testcases--) solve();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define quickread                     \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL);
#define pb push_back
#define all(x) x.begin(), x.end()
#define hii cout << "Hii there Sparky! \n"
#define endl '\n'
#define mod 1000000007
//#define mod 998244353
#define maxn 100010 //check the limits, dummy

void solve() {
    int n;
    cin >> n;
    int arr[n];
    int mx = 0;
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
        mx = max(arr[i], mx);
    }
    int arr2[n];
    int mn = INT_MAX;
    for (int i = 0; i < n; i++) {
        cin >> arr2[i];
        mn = min(arr2[i], mn);
    }
    cout << max(0LL, mn - mx + 1);
}

int32_t main() {
    quickread;
    int test = 1;
    //cin >> test;
    for (int i = 0; i < test; i++) {
        solve();
    }
    return 0;
}


/*
 *  Written by: Richw818
 *  Lang: C++17
 *  main.cpp
 */
#include<bits/stdc++.h>
using namespace std;
//Macros
#define ll long long
#define ld long double
#define ull unsigned long long
#define uint unsigned int
#define pb push_back
#define pf push_front
#define eb emplace_back
#define ef emplace_front
#define str string
#define fi first
#define se second
#define REP(i, n) for(int i = 0; i < (int)n; ++i)
#define sz(a) (int)(a.size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
//IO
template<class H, class T> void read(pair<H, T> &p);
template<class T> void read(vector<T>& v);
template<class T> void read(T& t){
    cin >> t;
}
template<class H, class... T> void read(H& h, T&... t){
    read(h);
    read(t...);
}
template<class T> void read(vector<T>& v){
    for(auto &t : v)
        read(t);
}
template<class H, class T> void read(pair<H, T> &p){
    read(p.fi, p.se);
}
void setIn(str s){
    freopen(s.c_str(), "r", stdin);
}
void setOut(str s){
    freopen(s.c_str(), "w", stdout);
}
void setIO(str s = ""){
    cin.tie(0)->sync_with_stdio(0);
    if(sz(s))
        setIn(s+".in"), setOut(s+".out");
}
//Debug
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<class H, class... T> void dbg(H& h, T&... t){
    dbg(h);
    dbg(t...);
}
#ifdef LOCAL
#define dbg(x...) cerr << "[" << #x << "] = ["; _print(x);
#else
#define dbg(x...)
#endif
//Constants
ll MODS[2] = {1000000007, 998244353};
const ll MOD = MODS[0];
const int INF = (int)1e9;
const ll LINF = (ll)1e18;
const ld PI = acos((ld)-1.0);
const int MAXN = (int)3e5+7;
//Code
void solve(){
    int n, m; read(n, m);
    vector<ll> h(n), w(m); read(h, w);
    sort(all(h));
    vector<ll> pref(n+1);
    for(int i = 1; i <= n; ++i)
        pref[i] = pref[i-1] + (i % 2 ? -h[i-1] : h[i-1]);
    ll ans = LINF;
    for(ll val : w){
        int ind = lower_bound(all(h), val) - h.begin();
        ll curr = 2 * pref[ind] - pref[n];
        curr += (ind % 2 ? val : -val);
        ans = min(ans, curr);
    }
    cout << ans;
}
int main(){
    setIO();
    int t = 1;
    //read(t);
    while(t--) solve();
    return 0;
}
/* stuff you should look for
    * int overflow, array bounds
    * special cases (n=1?)
    * do smth instead of nothing and stay organized
    * WRITE STUFF DOWN
    * DON'T GET STUCK ON ONE APPROACH
*/

#include <bits/stdc++.h>
using namespace std;
#include <math.h>
#include <iomanip>
#include <cstdint>
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,n) for (int i = 0; i < (n); ++i)
typedef long long ll;
using P = pair<int,int>;
const int INF=1001001001;
const int mod =998244353;
int main() {
  int N,M;
  cin>>N>>M;
  vector<ll>H(N),W(M);
  for(int i=0;i<N;i++){cin>>H[i];}
  for(int i=0;i<M;i++){cin>>W[i];}
  sort(H.begin(),H.end());
  vector<ll>l(N/2+1),r(N/2+1);
  for(int i=0;i<N/2;i++){
    l[i+1]=l[i]+H[2*i+1]-H[2*i];
    r[i+1]=r[i]+H[2*i+2]-H[2*i+1];//1インデックス
  }
  ll ans=INF;
  for(int i=0;i<M;i++){
    int x=lower_bound(H.begin(),H.end(),W[i])-H.begin();
    if((x&1)==1){x^=1;}//0インデックスならWは偶数番目としか組めない。
    chmin(ans,abs(H[x]-W[i])+l[x/2]+r[N/2]-r[x/2]);
  }
  cout<<ans<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define fore(i,a) for(auto &i:a)
#define all(x) (x).begin(),(x).end()
//#pragma GCC optimize ("-O3")
using namespace std;
void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); }
typedef long long ll; const int inf = INT_MAX / 2; const ll infl = 1LL << 60;
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; }
//---------------------------------------------------------------------------------------------------
/*---------------------------------------------------------------------------------------------------
　　　　　　　　　　　 ∧＿∧
　　　　　 ∧＿∧ 　（´<_｀ ）　 Welcome to My Coding Space!
　　　　 （ ´_ゝ`）　/　 ⌒i     @hamayanhamayan0
　　　　／　　　＼　 　  |　|
　　　 /　　 /￣￣￣￣/　　|
　 ＿_(__ﾆつ/　    ＿/ .| .|＿＿＿＿
　 　　　＼/＿＿＿＿/　（u　⊃
---------------------------------------------------------------------------------------------------*/

int N, M, X, Y;
int A[101010], B[101010], T[101010], K[101010];
vector<pair<int, pair<int,int>>> E[101010];
//---------------------------------------------------------------------------------------------------
template<typename T> using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;
int vis[101010];
ll D[101010];
ll dijk() {
    rep(i, 0, N) D[i] = infl;
    rep(i, 0, N) vis[i] = 0;

    min_priority_queue<pair<ll, int>> que;

    D[X] = 0;
    que.push({ 0, X });

    while (!que.empty()) {
        auto q = que.top(); que.pop();

        ll cst = q.first;
        int cu = q.second;

        if (cu == Y) return D[Y];

        if (vis[cu]) continue;
        vis[cu] = 1;

        fore(p, E[cu]) {
            int to = p.first;
            int T = p.second.first;
            int K = p.second.second;

            ll cst2 = (cst + K - 1) / K * K + T;
            if (chmin(D[to], cst2)) que.push({ D[to], to });
        }
    }

    return -1;
}
//---------------------------------------------------------------------------------------------------
void _main() {
	cin >> N >> M >> X >> Y;
	X--; Y--;
	rep(i, 0, M) {
		cin >> A[i] >> B[i] >> T[i] >> K[i];
		A[i]--; B[i]--;

        E[A[i]].push_back({ B[i], {T[i], K[i]} });
        E[B[i]].push_back({ A[i], {T[i], K[i]} });
	}

    ll ans = dijk();
    cout << ans << endl;
}

//#pragma GCC optimize ("O2")
//#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
//#include<atcoder/all>
//using namespace atcoder;
#include<cstdio>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	if ((tmp & ma0) ^ ma0) {
		int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
		tmp = tmp << dig & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += (72 - dig >> 3);
	}
	else {
		tmp = tmp & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += 8;
		if ((ct = *ci++) >= '0') {
			tmp = tmp * 10 + ct - '0';
			if (*ci++ == '0') {
				tmp = tmp * 10;
				ci++;
			}
		}
	}
	return tmp;
}
int tmp[100000], P[50000], Q[50000];
void pakuri_sort(int N, int A[]) {
	const int b = 8;
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

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

	int N = getint();

	ll kotae = 0;
	rep(i, N) {
		tmp[i] = getint();
		kotae += tmp[i];
	}
	rep(i, N) {
		int b = getint();

		if (i & 1) P[i >> 1] = (b - tmp[i] + 1000000000);
		else Q[i >> 1] = (b - tmp[i] + 1000000000);
	}

	pakuri_sort(N / 2, P);
	pakuri_sort(N / 2, Q);

	int k = N / 2 - 1;
	while (k >= 0) {
		int a = P[k] - 1000000000;
		int b = Q[k] - 1000000000;
		if (a + b <= 0) break;
		kotae += a + b;
		k--;
	}

	printf("%lld\n", kotae);

	Would you please return 0;
}


#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define setbits(x) __builtin_popcountll(x)
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define int long long int
#define ff first
#define ss second
#define float long double
void solve()
{
          int n=0,x=0,y=0;
          cin>>n>>x>>y;
          float dist=sqrt((float)x*(float)x+(float)y*(float)y);
          float temp=dist;
          int temp2=(int)temp;
          if((float)temp2 == dist)
          {
                  if((int)dist%n == 0)
                    {
                              cout<<dist/n<<"\n";
                              return;
                    }
          }
          for(int i=2;i<1e6;i++)
          {
                    if(dist < (float)(i*n))
                    {
                              cout<<i<<"\n";
                              return;
                    }
          }
}
signed main()
{
          ios_base::sync_with_stdio(false);
          cin.tie(0);
          cout.tie();
          int t;
          //cin>>t;
          t=1;
          while(t--)
          {
                    solve();
          }
          return 0;
}


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

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

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

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

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

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

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

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

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

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

using namespace templates;

vector<ll> func(){
    int n = in();
    vector<ll> A(n);
    vector<ll> B(n);
    foreach(i,A)i=in();
    foreach(i,B)i=in();
    vector<ll> AM(n,0);
    rep(i,n){
        chmax(AM[i],A[i]);
        if(i+1<n)chmax(AM[i+1],AM[i]);
    }
    ll CM = 0;
    vector<ll> res(n);
    rep(i,n){
        chmax(CM,AM[i] * B[i]);
        res[i] = CM;
    }

    return res;
}

int main(){
    vector<ll> ans = func();
    foreach(i,ans){
        cout << i << endl;
    }
  return 0;
}

#include <bits/stdc++.h>
// #include <atcoder/all>
// using namespace atcoder;
#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)
#define rep2(i, s, n) for (ll i = s; i < (ll)(n); i++)
#define repr(i, n) for (ll i = n; i >= 0; i--)
#define pb push_back
#define COUT(x) cout << (x) << "\n"
#define COUTF(x) cout << setprecision(21) << (x) << "\n"
#define ENDL cout << "\n"
#define DF(x) x.erase(x.begin())
#define ALL(x) x.begin(), x.end()
#define SORT(x) sort(ALL(x))
#define RSORT(x) sort(x.rbegin(), x.rend())
#define REVERSE(x) reverse(ALL(x))
#define MAX(x) *max_element(ALL(x))
#define MAXI(x) max_element(ALL(x)) - x.begin()
#define SUM(x) accumulate(ALL(x), 0ll)
#define COUNT(x, y) count(ALL(x), y);
#define ANS cout << ans << "\n"
#define YES cout << "YES\n";
#define NO cout << "NO\n";
#define Yes cout << "Yes\n";
#define No cout << "No\n";
#define init() \
  cin.tie(0);  \
  ios::sync_with_stdio(false)
#define LINE cerr << "[debug] line: " << __LINE__ << endl;
#define debug(x) cerr << "[debug] " << #x << ": " << x << endl;
#define debugV(v)                       \
  cerr << "[debugV] " << #v << ":";     \
  rep(z, v.size()) cerr << " " << v[z]; \
  cerr << endl;
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using mll = map<ll, ll>;
using qll = queue<ll>;
using P = pair<ll, ll>;
using vp = vector<P>;
using vs = vector<string>;

template <typename T>
inline istream& operator>>(istream& i, vector<T>& v) {
  rep(j, v.size()) i >> v[j];
  return i;
}

template <typename T1, typename T2>
inline istream& operator>>(istream& i, pair<T1, T2>& v) {
  return i >> v.first >> v.second;
}

constexpr ll INF = 0x3f3f3f3f3f3f3f3f;
constexpr ld PI = 3.141592653589793238462643383279;
ll get_digit(ll x) {
  return to_string(x).size();
}

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

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

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

void warshall_floyd(ll N, vvll& d) {
  rep(k, N) rep(i, N) rep(j, N) chmin(d[i][j], d[i][k] + d[k][j]);
}

signed main() {
  init();
  ll N;
  cin >> N;
  vs S(N);
  cin >> S;

  vvll D(100, vll(100, INF));
  rep(i, N) rep(j, N) {
    if (S[i][j] == '1') D[i][j] = 0;
    if (i == j) D[i][j] = 0;
  }

  warshall_floyd(N, D);
  ld ans = 0;
  rep(i, N) {
    ll c = 0;
    rep(j, N) if (D[j][i] == 0) c++;
    ans += 1.0 / c;
  }
  COUTF(ans);
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int              long long int
#define all(xs)          xs.begin(), xs.end()
#define rall(xs)         xs.rbegin(), xs.rend()
#define sz(x)            (int)((x).size())
#define pb               push_back
#define ppb              pop_back
#define pf               push_front
#define ppf              pop_front
#define mp               make_pair
#define ff               first
// #define ss               second
#define prec(n)          fixed<<setprecision(n)
#define debug(x)         cout << (#x) << " is " << (x) << "\n"
#define debug2(x, y)     cout << #x << "=" << x << "," << #y << "=" << y << "\n"
#define debug3(x, y,z)   cout << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << "\n"
#define yes              cout<<"YES";
#define no               cout<<"NO";
#define ll               cout<<"\n";
#define nil              0
#define inf              1e15
#define inf18            1e18
#define SZ               200005
int gcd(int A,int B){    return (B == 0) ? A : gcd(B, A % B);}
int lcm(int A,int B){    return A * B / gcd(A, B);}
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
const int nn=1e5+10;
bool permutation(vector<int>arr, int n)
{
    // Set to check the count
    // of non-repeating elements
    set<int> hash;

    int maxEle = 0;

    for (int i = 0; i < n; i++) {

        // Insert all elements in the set
        hash.insert(arr[i]);

        // Calculating the max element
        maxEle = max(maxEle, arr[i]);
    }

    if (maxEle != n)
        return false;

    // Check if set size is equal to n
    if (hash.size() == n)
        return true;

    return false;
}
void solve(){
    int n;cin>>n;
    map<int,int>m;
    set<int> ss;
    vector<int> a(n);
    for(auto &i:a){
        cin>>i;
    }
    if (permutation(a, n))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}
signed main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
    int t=1;
    // cin>>t;
    for(int i=0;i<t;i++){
        // cout<<"Case #"<<i+1<<": ";
        solve();
    }
}

#define _GLIBCXX_DEBUG
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

using namespace std;

int main() {
  int N;
  cin >> N;
  vector<int> A(N), check(N);
  for (int &x : A) cin >> x;
  for (int i = 0; i < N; i++) {
    if (check.at(A.at(i) - 1) == 1) {
      cout << "No" << endl;
      return 0;
    }
    check.at(A.at(i) - 1) = 1;
  }
  cout << "Yes" << endl;
  return 0;
}


#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <deque>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <ctime>
#include <iterator>
#include <bitset>
#include <numeric>
#include <list>
#include <iomanip>
#include <cassert>

#if __cplusplus >= 201103L
#include <array>
#include <tuple>
#include <initializer_list>
#include <unordered_set>
#include <unordered_map>
#include <forward_list>
#include <random>

using namespace std;

#define cauto const auto&
#define ALL(v) begin(v),end(v)
#else
#define ALL(v) (v).begin(),(v).end()
#endif

namespace{
typedef long long LL;
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;

#define VV(T) vector<vector< T > >

template <class T>
void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()){
	v.assign(a, vector<T>(b, t));
}
template <class T> inline bool chmin(T &x, const T &y){ if(y < x){ x = y; return true; } return false; }
template <class T> inline bool chmax(T &x, const T &y){ if(x < y){ x = y; return true; } return false; }
template <class F, class T>
void convert(const F &f, T &t){
	stringstream ss;
	ss << f;
	ss >> t;
}
template <class Con>
string concat(const Con &c, const string &spr){
	stringstream ss;
	typename Con::const_iterator it = c.begin(), en = c.end();
	bool fst = true;
	for(; it != en; ++it){
		if(!fst){ ss << spr; }
		fst = false;
		ss << *it;
	}
	return ss.str();
}

template <class Con, class Fun>
vector<typename Con::value_type> cfilter(const Con &c, Fun f) {
	vector<typename Con::value_type> ret;
	typename Con::const_iterator it = c.begin(), en = c.end();
	for(; it != en; ++it){
		if(f(*it)){
			ret.emplace_back(*it);
		}
	}
	return ret;
}
#if __cplusplus >= 201103L
template <class Con, class Fun>
auto cmap(const Con &c, Fun f) -> vector<decltype(f(*c.begin()))> {
	vector<decltype(f(*c.begin()))> ret;
	ret.reserve(c.size());
	for(const auto &x: c){
		ret.emplace_back(f(x));
	}
	return ret;
}
#endif

#if __cplusplus >= 201402L
#define lambda(e) ([&](const auto &_){ return (e); })
#define lambda2(e) ([&](const auto &_a, const auto &_b){ return (e); })
#endif

#define REP(i,n) for(int i=0;i<int(n);++i)
#define RALL(v) (v).rbegin(),(v).rend()
#define tget(t,i) get<i>(t)

#define MOD 1000000007LL
#define EPS 1e-8

void mainmain(){
	int n;
	cin >> n;
	const int m = 100010;
	vector<char> dp(m);
	dp[0] = 1;
	int s = 0;
	REP(i, n){
		int t;
		cin >> t;
		s += t;
		for(int j = m - 1; j >= t; --j){
			dp[j] |= dp[j - t];
		}
	}
	int ans = s;
	REP(i, m){
		if(dp[i]){ chmin(ans, max(i, s - i)); }
	}
	cout << ans << endl;
}

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

#include<iostream>
#include<vector>
#include<string>
#define rep(i, start, end) for (int i = (int)start; i < (int)end; ++i)
#define rrep(i, start, end) for (int i = (int)start - 1; i >= (int)end; --i)
#define all(x) (x).begin(), (x).end()
using namespace std;
using ll = long long;
template<typename T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return 0;}
template<typename T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return 0;}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N;
    cin >> N;
    vector<int> T(N);
    for (auto& t : T) {
        cin >> t;
    }
    vector<int> cumsum(N + 1, 0);
    rep(i, 0, N) {
        cumsum[i + 1] = cumsum[i] + T[i];
    }
    vector<vector<bool>> dp(N + 1, vector<bool>(100001, false));
    dp[0][0] = true;
    rep(i, 0, N) rep(j, 0, 100001) {
        if (!dp[i][j]) {
            continue;
        }
        int another = cumsum[i] - j;
        dp[i + 1][max(j + T[i], another)] = true;
        dp[i + 1][max(j, another + T[i])] = true;
    }
    rep(i, 0, 100001) {
        if (dp[N][i]) {
            cout << i << endl;
            return 0;
        }
    }
    return 0;
}


#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
#include <climits>
#include <cassert>
#include <fstream>

#define rep(i, n) for(int i = 0; i < n; i++)
#define per(i, n) for(int i = n - 1; i >= 0; i--)
using ll = long long;
#define vi vector<int>
#define vvi vector<vi>
#define vl vector<ll>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define mod 1000000007
using namespace std;
template<class T, class U>
T &chmax(T &a, const U &b){ if(a < b) a = b; return a; }
template<class T, class U>
T &chmin(T &a, const U &b){ if(a > b) a = b; return a; }
#define y first
#define x second
constexpr bool istest = false;
constexpr int n = 50;
ifstream file;
ofstream out;
void input_setup(){
	if(istest){
		cout << "write the in file number\n";
		string s;
		cin >> s;
		file.open("C:/Users/souta/downloads/ahc/tools/in/" + s + ".txt");
		if(file.fail()){
			cout << "the file was not found\n";
			return;
		}
		cin.rdbuf(file.rdbuf());
	}
}
//答えるときのやつ
string ans = "";
void output(){
	if(istest){
		out.open("C:/users/souta/downloads/ahc/tools/out.txt");
		if(out.fail()){
			cout << "the file was not found\n";
			return;
		}
		cout.rdbuf(out.rdbuf());
	}
	cout << ans << "\n";
}
pii st_pos;
vvi tiles(n, vi(n)), point(n, vi(n));
void inputs(){
	//start position
	cin >> st_pos.y >> st_pos.x;
	//tiles
	rep(i, n) rep(j, n) cin >> tiles[i][j];
	//points
	rep(i, n) rep(j, n) cin >> point[i][j];
}

//過去に同じ番号のタイルを通ったことがあるのかを確認する
bool checkVisited(const int &Y, const int &X, const vector<pii> &logs){
	int col = tiles[Y][X];
	for(auto a : logs){
		if(col == tiles[a.y][a.x]) return true;
	}
	return false;
}
//とりあえずBFSで探索してみる
int dy[] = {-1,1,0,0};
int dx[] = {0,0,-1,1};
char dir[] = {'U', 'D', 'L', 'R'};
void bfs(){
	priority_queue<pair<pii, int>> que;
	vvi checked(n, vi(n, -1));
	checked[st_pos.y][st_pos.x] = point[st_pos.y][st_pos.x];
	vector<vector<vector<pii>>> logs(n, vector<vector<pii>>(n));

	logs[st_pos.y][st_pos.x].push_back(make_pair(st_pos.y, st_pos.x));

	pii bestpos = st_pos;
	int mx = point[st_pos.y][st_pos.x];

	rep(loop, 10){

		vector<pii> temp = logs[bestpos.y][bestpos.x];
		logs = vector<vector<vector<pii>>>(n, vector<vector<pii>>(n));
		checked = vvi(n, vi(n, -1));
		logs[bestpos.y][bestpos.x] = temp;
		checked[bestpos.y][bestpos.x] = mx;
		que.push(make_pair(bestpos, mx));

		while(!que.empty()){
			pii pos; int score;
			tie(pos, score) = que.top();
			que.pop();
			if(checked[pos.y][pos.x] > score) continue;
			rep(i, 4){
				int Y = pos.y + dy[i];
				int X = pos.x + dx[i];
				if(Y >= n || X >= n || Y < 0 || X < 0) continue;
				if(checkVisited(Y, X, logs[pos.y][pos.x])) continue;

				int v = score + point[Y][X];
				if(checked[Y][X] == -1 || checked[Y][X] < v){
					que.push(make_pair(make_pair(Y, X), v));
					checked[Y][X] = v;
					logs[Y][X] = logs[pos.y][pos.x];
					logs[Y][X].push_back(make_pair(Y, X));
				}
			}
		}

		mx = 0;
		bestpos = st_pos;
		rep(i, n) rep(j, n){
			if(mx < checked[i][j]){
				bestpos = make_pair(i, j);
				mx = checked[i][j];
			}
		}
	}

	vector<pii> track = logs[bestpos.y][bestpos.x];
	pii last = st_pos;
	for(auto a : track){
		rep(i, 4){
			if(last.y + dy[i] == a.y && last.x + dx[i] == a.x){
				ans += dir[i];
				break;
			}
		}
		last = a;
	}
}
int main(){
	input_setup();
	inputs();

	bfs();

	output();
}

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

void used_tile(vector<vector<int> > &t,int x,int y)
{
  if(t[x][y]==t[x-1][y]) t[x-1][y]=-1;
  else if(t[x][y]==t[x+1][y]) t[x+1][y]=-1;
  else if(t[x][y]==t[x][y-1]) t[x][y-1]=-1;
  else if(t[x][y]==t[x][y+1]) t[x][y+1]=-1;
  t[x][y]=-1;
}
int cant_move(vector<vector<int> > t,int x,int y)
{
  if(t[x-1][y]==-1&&t[x+1][y]==-1&&t[x][y-1]==-1&&t[x][y+1]==-1) return 1;
  else return 0;
}
void can_move(vector<vector<int> > t,int x,int y,vector<int> &can)
{
  if(t[x-1][y]!=-1) can[2]=1;
  if(t[x+1][y]!=-1) can[3]=1;
  if(t[x][y-1]!=-1) can[0]=1;
  if(t[x][y+1]!=-1) can[1]=1;
}
void random(int &x,int &y,vector<int> can,vector<string> &answer){
  int select=rand()%can.size();
  if(select==0&&can[select]==1) {y=y-1; answer.push_back("L");}
  else if(select==1&&can[select]==1) {y=y+1;answer.push_back("R");}
  else if(select==2&&can[select]==1) {x=x-1;answer.push_back("U");}
  else if(select==3&&can[select]==1) {x=x+1;answer.push_back("D");}
}
void to_right(int &x,int &y,vector<int> can,vector<string> &answer)
{
  if(can[1]==1) {y=y+1;answer.push_back("R");}
  else if(can[3]==1) {x=x+1;answer.push_back("D");}
  else if(can[2]==1) {x=x-1;answer.push_back("U");}
  else if(can[0]==1) {y=y-1;answer.push_back("L");}
}
void circle(int &x,int &y,vector<int> can,vector<string> &answer,int &type)
{
  if(type==1){
    if(x>35) type=2;
    if(can[3]==1){x=x+1;answer.push_back("D");}
    else if(can[1]==1) {y=y+1;answer.push_back("R");}
    else if(can[0]==1) {y=y-1;answer.push_back("L");}
    else if(can[2]==1) {x=x-1;answer.push_back("U");}
  }
  else if(type==2){
    if(y>35) type=3;
    if(can[1]==1) {y=y+1;answer.push_back("R");}
    else if(can[3]==1) {x=x+1;answer.push_back("D");}
    else if(can[2]==1) {x=x-1;answer.push_back("U");}
    else if(can[0]==1) {y=y-1;answer.push_back("L");}
  }
  else if(type==3){
    if(x<15) type=4;
    if(can[2]==1){x=x-1;answer.push_back("U");}
    else if(can[1]==1) {y=y+1;answer.push_back("R");}
    else if(can[0]==1) {y=y-1;answer.push_back("L");}
    else if(can[3]==1) {x=x+1;answer.push_back("D");}
  }
  else if(type==4){
    if(y<15) type=1;
    if(can[0]==1) {y=y-1;answer.push_back("L");}
    else if(can[3]==1) {x=x+1;answer.push_back("D");}
    else if(can[2]==1) {x=x-1;answer.push_back("U");}
    else if(can[1]==1) {y=y+1;answer.push_back("R");}
  }
}
int main()
{
  vector<string> answer;
  vector<vector<int> > t(52,vector<int>(52));
  vector<vector<int> > p(52,vector<int>(52));
  int si,sj;
  cin>>si>>sj;
  si=si+1;
  sj=sj+1;
  for(int i=1;i<51;i++){
    for(int j=1;j<51;j++) cin>>t[i][j];
  }
  for(int i=1;i<51;i++){
    for(int j=1;j<51;j++) cin>>p[i][j];
  }
  for(int i=0;i<52;i++){
    t[0][i]=-1;
    t[51][i]=-1;
    t[i][0]=-1;
    t[i][51]=-1;
  }

  used_tile(t,si,sj);
  int flag=0;
  int type=1;
  while(flag==0){
    vector<int> can(4,0);
    can_move(t,si,sj,can);
    circle(si,sj,can,answer,type);
    used_tile(t,si,sj);
    flag=cant_move(t,si,sj);
  }
  for(int i=0;i<answer.size();i++) cout<<answer[i];
  cout<<endl;
}


/*ver 7*/
#include <bits/stdc++.h>
using namespace std;
void init() {cin.tie(0);ios::sync_with_stdio(false);cout << fixed << setprecision(15);}
using ll = long long;
using ld = long double;
using vl = vector<ll>;
using vd = vector<ld>;
using vs = vector<string>;
using vb = vector<bool>;
using vvl = vector<vector<ll>>;
using vvd = vector<vector<ld>>;
using vvs = vector<vector<string>>;
using vvb = vector<vector<bool>>;
using pll = pair<ll,ll>;
using mll = map<ll,ll>;
template<class T> using V = vector<T>;
template<class T> using VV = vector<vector<T>>;
#define each(x,v) for(auto& x : v)
#define reps(i,a,b) for(ll i=(ll)a;i<(ll)b;i++)
#define rep(i,n) for(ll i=0;i<(ll)n;i++)
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define mp make_pair
const ll INF = 1LL << 60;
#define CLR(mat,f) memset(mat, f, sizeof(mat))
#define IN(a, b, x) (a<=x&&x<=b)
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ) //被り削除
#define debug cout << "line : " << __LINE__ << " debug" << endl;
#define ini(...) int __VA_ARGS__; in(__VA_ARGS__)
#define inl(...) long long __VA_ARGS__; in(__VA_ARGS__)
#define ind(...) long double __VA_ARGS__; in(__VA_ARGS__)
#define ins(...) string __VA_ARGS__; in(__VA_ARGS__)
#define inc(...) char __VA_ARGS__; in(__VA_ARGS__)
void in(){}
template <typename T,class... U> void in(T &t,U &...u){ cin >> t; in(u...);}
template <typename T> void in1(T &s) {rep(i,s.size()){in(s[i]);}}
template <typename T> void in2(T &s,T &t) {rep(i,s.size()){in(s[i],t[i]);}}
template <typename T> void in3(T &s,T &t,T &u) {rep(i,s.size()){in(s[i],t[i],u[i]);}}
template <typename T> void in4(T &s,T &t,T &u,T &v) {rep(i,s.size()){in(s[i],t[i],u[i],v[i]);}}
template <typename T> void in5(T &s,T &t,T &u,T &v,T &w) {rep(i,s.size()){in(s[i],t[i],u[i],v[i],w[i]);}}
void out(){cout << endl;}
template <typename T,class... U> void out(const T &t,const U &...u){cout << t; if(sizeof...(u)) cout << " "; out(u...);}
void die(){cout << endl;exit(0);}
template <typename T,class... U> void die(const T &t,const U &...u){cout << t; if(sizeof...(u)) cout << " "; die(u...);}
template <typename T> void outv(T s) {rep(i,s.size()){if(i!=0)cout<<" ";cout<<s[i];}cout<<endl;}
template <typename T> void out1(T s) {rep(i,s.size()){out(s[i]);}}
template <typename T> void out2(T s,T t) {rep(i,s.size()){out(s[i],t[i]);}}
template <typename T> void out3(T s,T t,T u) {rep(i,s.size()){out(s[i],t[i],u[i]);}}
template <typename T> void out4(T s,T t,T u,T v) {rep(i,s.size()){out(s[i],t[i],u[i],v[i]);}}
template <typename T> void out5(T s,T t,T u,T v,T w) {rep(i,s.size()){out(s[i],t[i],u[i],v[i],w[i]);}}
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
template <typename T> T allSum(vector<T> a){T ans=T();each(it,a)ans+=it;return ans;}
ll ceilDiv(ll a,ll b) {return (a+b-1)/b;}
ld dist(pair<ld,ld> a, pair<ld,ld> b){return sqrt(abs(a.fi-b.fi)*abs(a.fi-b.fi)+abs(a.se-b.se)*abs(a.se-b.se));} // ２点間の距離
ll gcd(ll a, ll b) { return b != 0 ? gcd(b, a % b) : a; }
ll lcm(ll a,ll b){ return a / gcd(a,b) * b;}
template <class A, class B> inline bool chmax(A &a, const B &b) { return b > a && (a = b, true); }
template <class A, class B> inline bool chmin(A &a, const B &b) { return b < a && (a = b, true); }
#define YES(n) ((n) ? "YES" : "NO"  )
#define Yes(n) ((n) ? "Yes" : "No"  )
#define yes(n) ((n) ? "yes" : "no"  )

int main(){
    init();
    inl(a,b,w);w*=1000;
    ll mx=w/a;
    ll mn=ceil((ld)w/b);
    if(mx<mn)die("UNSATISFIABLE");
    out(mn,mx);
    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <iomanip>

using namespace std;

int a,b,w;
#define PI 3.14159265359 ;

int main()
{

  cin >> a >> b >> w;

  w*=1000;

  int min=0;
  int max=0;

  min = ceil((double)w/b);
  max = w/a;

  if(max < min){
    cout << "UNSATISFIABLE";
  }
  else{
    cout << min << " " << max;
  }

  return 0;

}