/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    set<ll> se;
    forn(i,n) {
        cin >> a; se.insert(a);
    }
    vector<string> d;
    for(auto itr:se) {
        d.pb(int_to_bin(itr));
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    map<ll,ll> ma;
    vector<string> d;
    forn(i,n) {
        cin >> a;
        if(ma[a]==0) d.pb(int_to_bin(a));
        ma[a]++;
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    unordered_map<ll,ll> ma;
    vector<string> d;
    forn(i,n) {
        cin >> a;
        if(ma[a]==0) {
            d.pb(int_to_bin(a));
            ma[a]++;
        }
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    //map<ll,ll> ma;
    set<ll> se;
    vector<string> d;
    forn(i,n) {
        cin >> a;
        if(se.find(a)==se.end()) d.pb(int_to_bin(a));
        se.insert(a);
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
//const ll N = (ll)1e5+5;
//string d[N];
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    vector<string> d(n);
    forn(i,n) {
        cin >> a; d[i] = int_to_bin(a);
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


/* Author : bitshar */
// #pragma GCC optimize ("-O3")
#include <bits/stdc++.h>

using namespace std;

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

ll MOD = 1e9+7;

#define forn(i,e)               for(ll i=0; i<e; i++)
#define forsn(i,s,e)            for(ll i=s; i<e; i++)
#define rforn(i,e)              for(ll i=e; i>=0; i--)
#define rforsn(i,s,e)           for(ll i=e; i>=s; i--)
#define ln                      "\n"
#define sp                      " "
#define mp                      make_pair
#define pb                      push_back
#define fi                      first
#define se                      second
#define INF                     1e18
#define NEGINF                  -1e18
#define fio                     ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define dbg(x)                  cout << #x << " = " << x << ln
#define all(x)                  x.begin(), x.end()

#define out1(x1)                cout << x1 << ln
#define out2(x1,x2)             cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3)          cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4)       cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5)    cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln

#define in1(x1)                 cin >> x1
#define in2(x1,x2)              cin >> x1 >> x2
#define in3(x1,x2,x3)           cin >> x1 >> x2 >> x3
#define in4(x1,x2,x3,x4)        cin >> x1 >> x2 >> x3 >> x4
#define in5(x1,x2,x3,x4,x5)     cin >> x1 >> x2 >> x3 >> x4 >> x5
#define in6(x1,x2,x3,x4,x5,x6)  cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6

#define arrin(a,n)              forn(i,n) cin >> a[i];
#define arrout(a,n)             forn(i,n) {cout << a[i] << " ";} cout << ln;

//#define DEBUG_MODE
const ll MAXDIG = 30;
string int_to_bin(ll n) {

    ll ind=0; string k="";
    while(ind<MAXDIG) {
        if(n&1) k='1'+k;
        else k='0'+k;
        n/=2;
        ind++;
    }
    return k;

}

string recur(vector<string> d, ll ind) {

    if(ind==MAXDIG) return "";
    ll n = d.size();
    vector<string> one,zero;
    forn(i,n) {
        if(d[i][ind]=='0') zero.pb(d[i]);
        else one.pb(d[i]);
    }
    if(zero.size()==0) return '0'+recur(d,ind+1);
    else if(one.size()==0) return '0'+recur(d,ind+1);
    else {
        string a = recur(zero,ind+1), b = recur(one,ind+1);
        if(a>b) return '1'+b;
        else return '1'+a;
    }
}

ll bin_to_int(string ans) {
    ll n = ans.length(),k=0;
    forn(i,n) {
        if(ans[n-1-i]=='1') k+=pow(2,i);
    }
    return k;
}

void solve() {

    ll n,a; cin >> n;
    map<ll,ll> ma;
    vector<string> d;
    forn(i,n) {
        cin >> a;
        if(ma[a]==0) {
            d.pb(int_to_bin(a));
            ma[a]++;
        }
    }
    string ans = recur(d,0);
    cout << bin_to_int(ans) << ln;
}

int main() {

    #ifdef DEBUG_MODE
    freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
    fio;
    int t=1;
    //cin >> t;
    int o=1;
    while(t--) {
        //cout << "Case #" << o << ": ";
        solve();
        o++;
    }
}


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

int n, low[N], high[N];
int getlow(int x){
    int res = 0;
    for(int i = 0;i < 15;i++)
        res += x & (1 << i);
    return res;
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    int x, bit = 1 << 15, mi = INF, mx, ans = 0;
    for(int i = 1;i <= n;i++){
        cin >> x;
        low[i] = getlow(x);
        high[i] = (x - low[i]) >> 15;
    }
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, low[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi; mi = INF;
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, high[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi;
    cout << ans << '\n';
}


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

int n, low[N], high[N];
int getlow(int x){
    int res = 0;
    for(int i = 0;i < 15;i++)
        res += x & (1 << i);
    return res;
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    int x, bit = 1 << 15, mi = INF, mx, ans = 0;
    for(int i = 1;i <= n;i++){
        cin >> x;
        low[i] = getlow(x);
        high[i] = (x - low[i]) >> 15;
    }
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, low[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi; mi = INF;
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, high[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi << 15;
    cout << ans << '\n';
}


#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;

int dfs(vector<int> vec, int d){
    if(d == -1) return 0;
    vector<int> v[2];
    int x = 1 << d;
    for(int i = 0;i < vec.size();i++)
        vec[i] & x ? v[1].push_back(vec[i]) : v[0].push_back(vec[i]);
    return v[0].size() == 0 ? dfs(v[1], d - 1) :
          (v[1].size() == 0 ? dfs(v[0], d - 1) :
           x + min(dfs(v[0], d - 1), dfs(v[1], d - 1)));
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    int n;
    cin >> n;
    vector<int> v(n);
    for(int i = 0;i < n;i++) cin >> v[i];
    cout << dfs(v, 29) << '\n';
}


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

int n, t, a[N], dp[35][N][2];
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    for(int i = 1;i <= n;i++) cin >> a[i];
    int now = 0, mx1, mx2, ans = 0, x;
    for(int i = 0;i < 31;i++){
        mx1 = mx2 = -1;
        for(int j = 1;j <= n;j++){
            x = (a[j] & (1 << i)) > 0;
            if(i == 0){
                dp[i][j][1] = x ^ 1;
                dp[i][j][0] = x;
            }
            else{
                dp[i][j][1] = dp[i-1][j][now] + ((x ^ 1) << i);
                dp[i][j][0] = dp[i-1][j][now] + (x << i);
            }
        }
        for(int j = 1;j <= n;j++){
            mx1 = max(dp[i][j][1], mx1);
            mx2 = max(dp[i][j][0], mx2);
        }
        //cout << mx1 << ' ' << mx2 << '\n';
        if(mx1 <= mx2) ans += (1 << i);
        now = mx1 <= mx2;
        //cout << now << '\n';
    }
    int res = 0;
    for(int i = 1;i <= n;i++) res = max(res, a[i] ^ ans);
    //cout << ans << ' ' << res << '\n';
    cout << res << '\n';
}


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

int n, t, a[N], dp[35][N][2];
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    for(int i = 1;i <= n;i++) cin >> a[i];
    int x = 0, y, ans = 0;
    for(int i = 0;i < 31;i++){
        y = 0;
        for(int j = 1;j <= n;j++)
            y |= (a[j] & (1 << i)) > 0;
        x += y << i;
    }
    for(int i = 1;i <= n;i++) ans = max(ans, a[i] ^ x);
    cout << ans << '\n';
}


#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;

int t, n;
int dfs(vector<int> vec, int d){
    if(d == -1) return 0;
    vector<int> v[2];
    int x = 1 << d;
    for(int i = 0;i < vec.size();i++)
        vec[i] & x ? v[1].push_back(vec[i]) : v[0].push_back(vec[i]);
    if(v[0].size() == 0) return dfs(v[1], d - 1);
    else if(v[1].size() == 0) return dfs(v[0], d - 1);
    else return x + min(dfs(v[0], d - 1), dfs(v[1], d - 1));
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    vector<int> v;
    for(int i = 1;i <= n;i++) cin >> t, v.push_back(t);
    cout << dfs(v, 29) << '\n';
}


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

int n, low[N], high[N];
int getlow(int x){
    int res = 0;
    for(int i = 0;i <= 15;i++)
        res += x & (1 << i);
    return res;
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    int x, bit = 1 << 15, mi = INF, mx, ans = 0;
    for(int i = 1;i <= n;i++){
        cin >> x;
        low[i] = getlow(x);
        high[i] = (x - low[i]) >> 15;
    }
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, low[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi; mi = INF;
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, high[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi << 15;
    cout << ans << '\n';
}


#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;

int dfs(vector<int> vec, int d){
    if(d == -1) return 0;
    vector<int> v[2];
    int x = 1 << d;
    for(int i = 0;i < vec.size();i++)
        vec[i] & x ? v[1].push_back(vec[i]) : v[0].push_back(vec[i]);
    if(v[0].size() == 0) return dfs(v[1], d - 1);
    else if(v[1].size() == 0) return dfs(v[0], d - 1);
    else return x + min(dfs(v[0], d - 1), dfs(v[1], d - 1));
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    int n;
    cin >> n;
    vector<int> v(n);
    for(int i = 0;i < n;i++) cin >> v[i];
    cout << dfs(v, 29) << '\n';
}


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

int n, low[N], high[N];
int getlow(int x){
    int res = 0;
    for(int i = 0;i <= 15;i++)
        res += x & (1 << i);
    return res;
}
int main(){
    #ifdef Irene
    freopen("in.txt", "r", stdin);
    #endif // Irene
    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    int x, bit = 1 << 16, mi = INF, mx, ans = 0;
    for(int i = 1;i <= n;i++){
        cin >> x;
        low[i] = getlow(x);
        high[i] = (x - low[i]) >> 16;
    }
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, low[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi; mi = INF;
    for(int i = 0;i < bit;i++){
        mx = 0;
        for(int j = 1;j <= n;j++)mx = max(mx, high[j] ^ i);
        mi = min(mi, mx);
    }
    ans += mi << 16;
    cout << ans << '\n';
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
int fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    int sum1=0,sum2=0;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=i;
             break;
         }
    }
    if(k==-1||k==l)
      return fun(l,r,le-1);
    else
      {
    //      cout<<le<<" ";
          return (int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));
      }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }
    int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
int fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    int sum1=0,sum2=0;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=l;
             break;
         }
    }
    if(k==-1||k==r)
      return fun(l,r,le-1);
    else
      return (int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));

}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }
    int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
long long fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=i;
             break;
         }
    }
    if(k==-1||k==l)
      return fun(l,r,le-1);
    else
      {
    //      cout<<le<<" ";
          return (long long int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));
      }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }
    long long int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
int fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    int sum1=0,sum2=0;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=l;
             break;
         }
    }
    if(k==-1||k==l)
      return fun(l,r,le-1);
    else
      return (int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));

}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }

    int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
int fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    int sum1=0,sum2=0;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=i;
             break;
         }
    }
    if(k==-1||k==l)
      return fun(l,r,le-1);
    else
      {
    //      cout<<le<<" ";
          return (int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));
      }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }

    int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
long long fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=i;
             break;
         }
    }
    if(k==-1)
      return fun(l,r,le-1);
    else if(k==l)
      return (long long)pow(2,le)+fun(l,r,le-1);
    else
      {
          return (long long int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));
      }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }
    long long int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include<bits/stdc++.h>
using namespace std;
int a[100001][30];
long long fun(int l,int r,int le)
{
    if(le<0)
     return 0;
    int k=-1;
    for(int i=l;i<=r;i++)
    {
        if(a[i][le]==1)
         {
             k=i;
             break;
         }
    }
    if(k==-1||k==l)
      return fun(l,r,le-1);

    else
      return (long long int)pow(2,le)+min(fun(l,k-1,le-1),fun(k,r,le-1));

}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n;
    cin>>n;
    int l[n+1];
    for(int i=1;i<=n;i++)
     cin>>l[i];
  sort(l+1,l+1+n);
    for(int i=1;i<=n;i++)
    {
        int x=l[i];
        for(int j=0;j<30;j++)
        {
            if(x&(1<<j))
             a[i][j]=1;
        }
    }
    long long int k=fun(1,n,29);
     cout<<k<<"\n";
}


#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <bitset>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <sstream>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

#define OO 2e9+10
#define pb push_back
#define deb(a)    cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl;
#define ConPnt(a)   {for(auto it: a){cout<<it<<", ";}cout<<endl;}
#define MapPnt(a)   {for(auto it: a){cout<<it.first<<": "<<it.second<<", ";}cout<<endl;}

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

template<class T>T sqr(T a){
    return a*a;
}
template<class T> T abs(T x){
    if(x<0) return -x;
    return x;
}

const double eps = 1e-8;
const double pi = acos(-1.0);

int br[100010];
int ar[35];

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("output.txt","w",stdout);

    int i,n,j;
    while(1==scanf("%d",&n))
    {
        memset(ar,0,sizeof ar);
        for(i=0;i<n;i++)
        {
            scanf("%d",&br[i]);
            for(j=0;j<=30;j++)
            {
                if((br[i]&(1<<j)))
                    ar[j]++;
            }
        }
//        for(i=0;i<=30;i++)
//            cout<<ar[i]<<" ";
//        cout<<endl;
        int sum = 0;
        for(i=0;i<=30;i++)
        {
            if(ar[i])
                sum = sum + (1<<i);
        }
        int mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^br[i]);
        printf("%d\n",mx);
    }

    return 0;
}


#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <bitset>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <sstream>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

#define OO 2e9+10
#define pb push_back
#define deb(a)    cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl;
#define ConPnt(a)   {for(auto it: a){cout<<it<<", ";}cout<<endl;}
#define MapPnt(a)   {for(auto it: a){cout<<it.first<<": "<<it.second<<", ";}cout<<endl;}

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

template<class T>T sqr(T a){
    return a*a;
}
template<class T> T abs(T x){
    if(x<0) return -x;
    return x;
}

const double eps = 1e-8;
const double pi = acos(-1.0);

int br[100010];
int ar[100010];

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("output.txt","w",stdout);

    int i,n,j,k;
    while(1==scanf("%d",&n))
    {
//        memset(ar,0,sizeof ar);
        for(i=0;i<n;i++)
        {
            scanf("%d",&br[i]);
            ar[i]=br[i];
        }

        int sum = 0;
        for(i=30;i>=0;i--)
        {
            sort(&br[0],&br[n]);
            if(br[n-1]&(1<<i))
                k = 1,sum+=(1<<i);
            else
                k = 0;
            for(j=0;j<n;j++)
            {
                if(k==1)
                {
                    if(br[j]&(1<<i))
                        br[j]-=(1<<i);
                    else
                        br[j]+=(1<<i);
                }
            }
        }
        int mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^ar[i]);
        printf("%d\n",mx);
    }

    return 0;
}


#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <bitset>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <sstream>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

#define OO 2e9+10
#define pb push_back
#define deb(a)    cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl;
#define ConPnt(a)   {for(auto it: a){cout<<it<<", ";}cout<<endl;}
#define MapPnt(a)   {for(auto it: a){cout<<it.first<<": "<<it.second<<", ";}cout<<endl;}

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

template<class T>T sqr(T a){
    return a*a;
}
template<class T> T abs(T x){
    if(x<0) return -x;
    return x;
}

const double eps = 1e-8;
const double pi = acos(-1.0);

ll br[100010];
ll ar[100010];
ll cr[100010];

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("output.txt","w",stdout);

    ll i,n,j,k;
    while(1==scanf("%lld",&n))
    {
        for(i=0;i<n;i++)
        {
            scanf("%lld",&br[i]);
            ar[i]=br[i];
        }

        ll sum = 0;
        sort(&br[0],&br[n]);
        for(i=30;i>=0;i--)
        {
            for(j=0;j<n;j++)
                cr[j]=br[j];

            if(br[n-1]&(1LL<<i))
                k = 1,sum+=(1LL<<i);
            else
                k = 0;

            for(j=0;j<n;j++)
            {
                if(k==1)
                {
                    if(br[j]&(1LL<<i))
                        br[j]-=(1LL<<i);
                    else
                        br[j]+=(1LL<<i);
                }
            }
            sort(&br[0],&br[n]);
            if(br[n-1]>cr[n-1])
            {
                for(j=0;j<n;j++)
                    br[j]=cr[j];
                sum-=(1LL<<i);
            }
        }
//        cout<<sum<<endl;

        sort(&ar[0],&ar[n]);
        ll mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^ar[i]);

        ll ans = min(mx,ar[n-1]);

        for(i=0;i<n;i++)
            br[i]=ar[i];

        sum = 0;
        for(i=0;i<=30;i++)
        for(i=30;i>=0;i--)
        {
            for(j=0;j<n;j++)
                cr[j]=br[j];

            if(br[n-1]&(1LL<<i))
                k = 1,sum+=(1LL<<i);
            else
                k = 0;

            for(j=0;j<n;j++)
            {
                if(k==1)
                {
                    if(br[j]&(1LL<<i))
                        br[j]-=(1LL<<i);
                    else
                        br[j]+=(1LL<<i);
                }
            }
            sort(&br[0],&br[n]);
            if(br[n-1]>cr[n-1])
            {
                for(j=0;j<n;j++)
                    br[j]=cr[j];
                sum-=(1LL<<i);
            }
        }
//        cout<<sum<<endl;
        mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^ar[i]);
         ans = min(mx,ans);
        printf("%d\n",ans);
    }

    return 0;
}


#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <bitset>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <sstream>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

#define OO 2e9+10
#define pb push_back
#define deb(a)    cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl;
#define ConPnt(a)   {for(auto it: a){cout<<it<<", ";}cout<<endl;}
#define MapPnt(a)   {for(auto it: a){cout<<it.first<<": "<<it.second<<", ";}cout<<endl;}

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

template<class T>T sqr(T a){
    return a*a;
}
template<class T> T abs(T x){
    if(x<0) return -x;
    return x;
}

const double eps = 1e-8;
const double pi = acos(-1.0);

int br[100010];
int ar[100010];

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("output.txt","w",stdout);

    int i,n,j,k;
    while(1==scanf("%d",&n))
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",&br[i]);
            ar[i]=br[i];
        }

        int sum = 0;
        for(i=30;i>=0;i--)
        {
            sort(&br[0],&br[n]);
            if(br[n-1]&(1<<i))
                k = 1,sum+=(1<<i);
            else
                k = 0;
            for(j=0;j<n;j++)
            {
                if(k==1)
                {
                    if(br[j]&(1<<i))
                        br[j]-=(1<<i);
                    else
                        br[j]+=(1<<i);
                }
            }
        }
        sort(&ar[0],&ar[n]);
        int mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^ar[i]);
        int ans = min(mx,ar[n-1]);

        for(i=0;i<n;i++)
            br[i]=ar[i];

        for(i=0;i<=30;i++)
        {
            sort(&br[0],&br[n]);
            if(br[n-1]&(1<<i))
                k = 1,sum+=(1<<i);
            else
                k = 0;
            for(j=0;j<n;j++)
            {
                if(k==1)
                {
                    if(br[j]&(1<<i))
                        br[j]-=(1<<i);
                    else
                        br[j]+=(1<<i);
                }
            }
        }
        mx = 0;
        for(i=0;i<n;i++)
            mx = max(mx,sum^ar[i]);
        ans = min(ans,mx);

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

    return 0;
}


#!/usr/bin
from sys import stdin

def IMP( n, s, t, shuffle ):
    if s == t:
        return 0
    beg = shuffle[s-1]
    count = 1
    while beg != t:
        if beg == s:
            return -1
        count += 1
        beg = shuffle[beg-1]
    return count

n, s, t = map( int, stdin.readline().split() )
print IMP( n, s, t, map(int, stdin.readline().split()) )


r=lambda:map(int,raw_input().split())
n,s,t=r()
a=r()
for i in range(n):
    if s==t:print i;exit()
    s=a[s-1]
print -1


n,s,d = map(int, raw_input().split());

p = map(int, raw_input().split());

for i in range(n):
    p[i] -= 1;

ans = 0;
s -= 1;
d -= 1;
while 1:
    if s == d:
        break;
    else:
        if p[s] == -1:
            ans = -1;
            break;
        else:
            ans += 1;
            tmp = p[s];
            p[s] = -1;
            s = tmp;

print ans;


import sys,math

def perm(i):
    return p[i-1]

hulp=[int(x) for x in sys.stdin.readline().split()]
n,s,t=hulp[0],hulp[1],hulp[2]
p=[int(x) for x in sys.stdin.readline().split()]

if s==t:
    print 0
else:
    teller=1
    while perm(s)!=t and teller<=n:
        teller+=1
        s=perm(s)
    if teller>n:
        print -1
    else:
        print teller


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == s :
	print -1
	quit()
else if c == t :
	print 0
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0

if s == t :
	print 0
	quit()
c = p[s]

count +=1
if c == t:
	print 1
	quit()
if c == s :
	print -1
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == t :
	print 0
	quit()
elif c == s :
	print -1
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == s :
	print -1
	quit()
elif c == t :
	print 0
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == t :
	print count
	quit()
elif c == s :
	print -1
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == t:
	if c==s:
		print 0
	else:
		print 1
	quit()
elif c == s :
	print -1
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


[n,s,t] = map(int, raw_input().split())
p = map(int, raw_input().split())
p = [0]+p
count = 0
c = p[s]
count +=1
if c == s :
	print -1
	quit()
while c != s:
	c = p[c]
	count += 1
	if(c == t):
		print count
		quit()
print -1


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
from sets import * #Set
import calendar
import heapq
import math
import copy
import itertools
myread = lambda : map(int,raw_input().split())
def solver():
    n,s,t = myread()
    shuffle = myread()
    if s == t:
        print 0
        return
    start_p = s
    now_p = s
    cnt = 0
    while True:
        next_p = shuffle[now_p-1]
        cnt += 1
        if next_p == t:
            break
        if next_p == start_p:
            print -1
            return
        now_p = next_p
    print cnt

if __name__ == "__main__":
    solver()


def f(n, s, t):
    l = map(int, raw_input().split())
    l = map(lambda x:x-1, l)
    s -= 1
    t -= 1
    count = 0
    flag = True
    for _ in xrange(n+1):
        if s == t:
            flag = False
            break
        else:
            s = l[s]
            count += 1
    if  flag:
        return -1
    return count
n, s, t = map(int, raw_input().split())
print f(n, s, t)


def cycle_decomp(p,n):
  color  = [0]*n
  start  = 0
  currc  = 1

  while 1:
    while start<n and color[start]: start += 1
    if start==n: break
    cycle_ptr = start

    while not color[cycle_ptr]:
      color[cycle_ptr] = currc
      cycle_ptr = p[cycle_ptr]

    start += 1
    currc += 1

  return color

n,s,t = map(int, raw_input().split())
s,t = s-1,t-1
A = [int(x)-1 for x in raw_input().split()]
color = cycle_decomp(A,n)
if color[s-1] == color[t-1]:
  shuffles = 0
  while s!=t: s,shuffles=A[s],shuffles+1
  print shuffles
else:
  print -1


def cycle_decomp(p,n):
  color  = [0]*n
  start  = 0
  currc  = 1

  while 1:
    while start<n and color[start]: start += 1
    if start==n: break
    cycle_ptr = start

    while not color[cycle_ptr]:
      color[cycle_ptr] = currc
      cycle_ptr = p[cycle_ptr]

    start += 1
    currc += 1

  return color

n,s,t = map(int, raw_input().split())
s,t = s-1,t-1
A = [int(x)-1 for x in raw_input().split()]
color = cycle_decomp(A,n)
if color[s] == color[t]:
  shuffles = 0
  while s!=t: s,shuffles=A[s],shuffles+1
  print shuffles
else:
  print -1


n_s_t=raw_input()
p_s=raw_input()
n_s_t=n_s_t.split()
n=int(n_s_t[0])
s=int(n_s_t[1])
t=int(n_s_t[2])
result=0
start=s-1
p_s=p_s.split()

for i in range(n):
    p_s[i]=int(p_s[i])

while True:
    if start==t-1:
        break
    result+=1
    start=p_s[start]-1
    if start==s-1:
        result=-1
        break

print result


#br = open('b.in')
f = lambda: map(int, raw_input().split())
n, s, t = f()
b = f()
a = [x + 1 for x in range(n)]
e = a
k = 0
while 1:
  c = [0 for x in range(n)]
  for i in range(n):
    c[b[i] - 1] = a[i]
  k += 1
  if c.index(s) == t - 1:
    break
  a = c
  if c == e:
    print -1
    exit()
print k


#br = open('b.in')
f = lambda: map(int, raw_input().split())
n, s, t = f()
b = f()
a = [x + 1 for x in range(n)]
e = a
k = 0
while 1:
  if a.index(s) == t - 1:
    break
  c = [0 for x in range(n)]
  for i in range(n):
    c[b[i] - 1] = a[i]
  k += 1
  a = c
  if c == e:
    print -1
    exit()
print k


f = lambda: map(int, raw_input().split())
n, s, t = f()
b = f()
c, k = s, 0
while 1:
  if c == t: break
  c = b[c - 1]
  k += 1
  if c == s:
    print -1
    exit()
print k


r=lambda:map(int, raw_input().split())
n,s,t=r()
p=r()
i=0
a=[0]*n
b=False
while s != t:
    if a[s-1]:
        b=True
        break
    a[s-1]=1
    s = p[s-1]
    i+=1
print -1 if b else i


'''

   			 ||Sri:||

                      __|
 ______________|_________________________
      |    |   ___|    |    |    ___|      |      |    |___
 /\  /\    |   |___    |    |   |___|      |      |    |___|
/  \/  \   |   ___|    |    |         |_/    |___|    |___

I am a beginner. Feel free to send tutorials/help to srinivasan1995@gmail.com.

Codeforces, SPOJ handle: desikachariar.
Hackerrank, Codechef handle: Prof_Calculus.

Advises/Help are welcome. You will definitely get a thanks in return. Comments to be avoided.

College: International Institute of Information Technology, Bangalore.

'''

import math

def fn():
	n, s, t = [int(x) for x in raw_input().split(' ')]
	ls = [0] + [int(x) for x in raw_input().split(' ')]
	count = 0
	while count <= n:
		if s == t:
			print count
			return 0
		s = ls[s]
		count += 1
	print -1

if __name__ == '__main__':
	fn()


R=lambda:map(int,raw_input().split())

inp_L = R()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = R()
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n-1:
    ctr += 1; pos = L[pos-1]+1;

print ctr if ctr != n else -1


R=lambda:map(int,raw_input().split())

inp_L = R()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = R()
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n-1:
    ctr += 1; pos = L[pos-1]+1;

print ctr if ctr != n-1 else -1


#/usr/bin/env python

R=lambda:map(int,raw_input().split())

inp_L = R()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = R()
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n:
    ctr += 1; pos = L[pos-1]+1;

print ctr if ctr != n else -1


get_input = lambda: map(int, raw_input().split())
inp_L = get_input()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = get_input()
s -= 1; n -= 1; t -= 1;
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n:
    ctr += 1; pos = L[pos];

print ctr if ctr != n else -1


R=lambda:map(int,raw_input().split())

inp_L = R()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = R()
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n:
    ctr += 1; pos = L[pos-1]+1;

print ctr if ctr != n else -1


#!/usr/bin/env python

get_input = lambda: map(int, raw_input().split())
inp_L = get_input()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = get_input()
s -= 1; n -= 1; t -= 1;
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n:
    ctr += 1; pos = L[pos];

print ctr if ctr != n else -1


get_input = lambda:map(int, raw_input().split())
inp_L = get_input()
n = inp_L[0]; s = inp_L[1]; t = inp_L[2];
L = get_input()
s -= 1; n -= 1; t -= 1;
for x in range(len(L)): L[x] -= 1
pos = s; ctr = 0;
while pos != t and ctr != n:
    ctr += 1; pos = L[pos];

print ctr if ctr != n else -1


import sys
n, s, t = map(int, raw_input().split())
p = raw_input().split(' ')

psn = s-1
kol = 0
bilo = set()
while True:
    if psn == t-1:
        break

    bilo.add(psn)

    psn = int(p[psn])-1
    if psn in bilo:
        print -1
        sys.exit(0)
    else:
        kol+=1

print kol


n, s, t = map(int, raw_input().split())
p = raw_input().split(' ')

psn = s-1
kol = 0
while True:
    if psn == t-1:
        break

    befor = psn
    psn = int(p[psn])-1
    if befor > psn:
        kol+=1
        break
    elif befor == psn:
        break
    else:
        kol+=1

if psn == t-1:
    print kol
else:
    print -1


n, s, t = map(int, raw_input().split())
p = raw_input().split(' ')

psn = s-1
kol = 0
while True:
    befor = psn
    psn = int(p[psn])-1
    if befor > psn:
        kol+=1
        break
    elif befor == psn:
        break
    else:
        kol+=1
if psn == t-1:
    print kol
else:
    print -1


n, s, t = map(int, raw_input().split())
p = map(int, raw_input().split())
r = 0
x = s
while x != t:
	if r and x == s:
		r = -1
		break
	x = p[x - 1]
	r += 1
print r


n, s, t = map(int, raw_input().split())
l = map(int, raw_input().split())
for i in range(n):
  if s == t:
    print i
    exit()
  s = l[s-1]
print -1


n, s, t = map(int, raw_input().split())
s -= 1
t -= 1
ps = map(lambda x: int(x)-1, raw_input().split())
visited = [False]*n
visited[s] = True
time = 0
while s != t and not visited[ps[s]]:
	s = ps[s]
	visited[s] = True
	time += 1
if s != t:
	print -1
else:
	print time


import sys

def readints() :
    l = sys.stdin.readline()
    return map(int, l.split(' '))

def readstring() :
    l = sys.stdin.readline()[:-1]
    return l

def readint() :
    l = sys.stdin.readline()
    return int(l)

def clearchars(s, chars) :
    for c in chars :
        s = s.replace(c, '')
    return s

def gcd(a, b) :
    if (a < b ) :
        a, b = b, a
    if b == 0 :
        return a
    return gcd(b, a % b)

def hist(a) :
    h = {}
    for x in a :
        try :
            h[x] += 1
        except KeyError :
            h[x] = 1
    return h

def lucky(n) :
    s = set(str(n))
    return all(map(lambda x: x in '47', s))

def yslice(a, j) :
    return map(lambda x: x[j], a)

def dist2(a, b) :
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

def chain_len(a) :
    l = .0
    for d, e in zip(a, a[1:]) :
        l += dist2(d, e)
    return l

def is_prime(x) :
    sq = int(x ** 0.5)
    for i in range(2, sq + 1) :
        if x % i == 0 :
            return False
    return True

digits = '0123456789'

def noe() :
    print "NO"
    exit(0)

def yese() :
    print "YES"
    exit(0)

n, s, t = readints()
p = [None] + readints()
i = 0
while (s != t and i <= n) :
     s = p[s]
     i += 1

if i > n :
    print -1
else :
    print i


n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
flag = [False]*(n+1)

cnt = 0
bp = s
while True:
    if flag[bp] == True:
        cnt = -1
        break
    if t == bp:
        break
    flag[bp] = True
    bp = p[bp]
    cnt += 1

print cnt


'''
n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
flag = [False]*(n+1)

cnt = 0
bp = s
while True:
    if flag[bp] == True:
        cnt = -1
        break
    if t == bp:
        break
    flag[bp] = True
    bp = p[bp]
    cnt += 1

print cnt
'''

from sys import stdin

def line():
    return stdin.readline().strip()

n, s, t = map(int, line().split())
p = [0] + map(int, line().split())
flag = [False]*(n+1)

cnt = 0
bp = s
while t != bp:
    if flag[bp]:
        cnt = -1
        break
    flag[bp] = True
    bp = p[bp]
    cnt += 1
print cnt


'''
n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
flag = [False]*(n+1)

cnt = 0
bp = s
while True:
    if flag[bp] == True:
        cnt = -1
        break
    if t == bp:
        break
    flag[bp] = True
    bp = p[bp]
    cnt += 1

print cnt
'''

from sys import stdin

def line():
    return stdin.readline().strip()

n, s, t = map(int, line().split())
p = [0] + map(int, line().split())

cnt = 0
bp = s
while t != bp:
    if flag[bp]:
        cnt = -1
        break
    flag[bp] = True
    bp = p[bp]
    cnt += 1
print cnt


ar=[1]
(n,s,t)=map(int,raw_input().split())
ar+=map(int,raw_input().split())
mark=[0]*(n+4)
pos=s
flag=True
count=0
while(True):
    if(pos==t):
        break
    if(mark[ar[pos]]==1):
        flag=False
        break
    mark[pos]=1
    pos=ar[pos]
    count+=1
if(flag==False): print -1
else: print count


n, s, t = map(int, raw_input().split())
a = map(int, raw_input().split())
if s == t:
  print 0
else:
  b, ans = s, 0
  for _ in xrange(n):
    b = a[b - 1]
    ans += 1
    if b == t:
      print ans
      exit(0)
  print -1


n , s , t = map(int , raw_input().split())
p = [x - 1 for x in map(int , raw_input().split())]
s0 = s
answer = 0
while s != t:
    s = p[s]
    answer += 1
    if s == s0:
        print -1
        exit(0)

print answer


n , s , t = map(int , raw_input().split())
p = [x - 1 for x in map(int , raw_input().split())]
s0 = s
s -= 1
t -= 1
answer = 0
while s != t:
    s = p[s]
    answer += 1
    if s == s0:
        print -1
        exit(0)

print answer


n , s , t = map(int , raw_input().split())
p = map(int , raw_input().split())
for i in range(n):
    if s == t:
        print i
        exit(0)
    s = p[s - 1]

print -1


r=lambda:map(int,raw_input().split())
n,s,t=r()
a=r()
for i in range(n):
    if s==t:print i;exit()
    s=a[s-1]
print -1


import sys
q,w,e=raw_input().split(" ")
l=raw_input().split(" ")
n=int(q)
a=int(w)
b=int(e)
k=0
l=list(map(int,l))
if(a==b):
    print"0"
else:
    for i in range(len(l)):
        if((l[i]==i+1 and b==i+1)or(l[i]==i+1 and a==i+1)):
            print"-1"
            quit()
    while(a!=b):
        x=l[a-1]
        a=x
        k=k+1

    print k


import sys
q,w,e=raw_input().split(" ")
l=raw_input().split(" ")
n=int(q)
a=int(w)
b=int(e)
k=0
l=list(map(int,l))
if(a==b):
    print"0"
else:
    for i in range(len(l)):
        if(l[i]==i+1 and b==i+1):
            print"-1"
            quit()
    while(a!=b):
        x=l[a-1]
        a=x
        k=k+1
    print k


import sys
q,w,e=raw_input().split(" ")
l=raw_input().split(" ")
n=int(q)
a=int(w)
b=int(e)
k=0
l=list(map(int,l))
if(a==b):
    print"0"
else:
    for i in range(len(l)):
        if((l[i]==i+1 and b==i+1)or(l[i]==i+1 and a==i+1)):
            print"-1"
            quit()
    while(a!=b):
        if(k>n):
            print"-1"
            quit()
        else:
            x=l[a-1]
            a=x
            k=k+1

    print k


#!/usr/bin/python

n,s,t = map(int,raw_input().split())
p = []
p = map(int,raw_input().split())

a = [i for i in range(1,n+1)]
d = dict(zip(a,p))
x = d[s]
count = 0
if x == t:
        print count
else:
        for i in range(n):
                count = count + 1
                if x == t:
                        print count
                        break
                else:
                        x = d[x]

if count == n:
        print "-1"


#!/usr/bin/python

n,s,t = map(int,raw_input().split())
p = []
p = map(int,raw_input().split())

a = [i for i in range(1,n+1)]
d = dict(zip(a,p))
x = d[s]
count = 0
if s == t:
        print count
else:
        for i in range(n):
                count = count + 1
                if x == t:
                        print count
                        break
                else:
                        x = d[x]

if count == n:
        print "-1"


n, s,t = map(int, raw_input().split())

l = map(int, raw_input().split())

ans = 0

cur = s

while cur != t or (cur == s and ans > 0):
    cur = l[s-1]
    ans += 1

if s == t:
    ans = 0
elif cur == s and ans > 0:
    ans = 1
print ans


n, s,t = map(int, raw_input().split())

l = map(int, raw_input().split())

ans = 0

cur = s

while cur != t and not (cur == s and ans > 0):
    cur = l[cur-1]
    ans += 1

if s == t:
    ans = 0
elif cur == s and ans > 0:
    ans = 1
print ans


n, s,t = map(int, raw_input().split())

l = map(int, raw_input().split())

ans = 0

cur = s

while cur != t and not (cur == s and ans > 0):
    cur = l[s-1]
    ans += 1

if s == t:
    ans = 0
elif cur == s and ans > 0:
    ans = 1
print ans


n, s,t = map(int, raw_input().split())

l = map(int, raw_input().split())

ans = 0

cur = s

while cur != t and not (cur == s and ans > 0):
    cur = l[cur-1]
    ans += 1

if s == t:
    ans = 0
elif cur == s and ans > 0:
    ans = -1
print ans


n,s,t=map(int,raw_input().split())
ops=map(int,raw_input().split())
dic=set();a=s;st=0;f=0
while 1:
    if a==t:
        f=1;break
    elif a in dic:
        f=0;break
    dic.add(a)
    a=ops[a-1]
    st+=1
print st if f else -1


n,a,b = map(int,raw_input().split())
a = a-1
b = b-1
s = map(lambda x:int(x)-1,raw_input().split())
c = [0]*n
#print a,b,s,c
while 1:
	#print a,b,c
	if c[a]==0:
		c[a]=1
		a = s[a]
		if a==b:
			break
	else:
		print -1
		exit(0)
	#print a,b,c
c[b]=0
print sum(c)


n,a,b = map(int,raw_input().split())
a = a-1
b = b-1
s = map(lambda x:int(x)-1,raw_input().split())
c = [0]*n
if a==b:
	print 0
	exit(0)
while 1:
	#print a,b,c
	if c[a]==0:
		c[a]=1
		a = s[a]
		if a==b:
			break
	else:
		print -1
		exit(0)
	#print a,b,c
c[b]=0
print sum(c)


n,s,t = map(int,raw_input().split())
a = map(int,raw_input().split())
counter = 0
prev_s = s
while True :
    if s==t :
        break
    s = a[s-1]
    counter += 1
    if s==prev_s :
        counter = -1
        break
print counter


n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
k = s
c = 0
while not ((k == t) or ((k == s) and (c > 0))):
	k = p[k]
	c += 1
if (k == t):
	print c
else:
	print "-1"rere


n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
k = s
c = 0
while not ((k == t) or ((k == s) and (c > 0))):
	k = p[k]
	c += 1
if (k == t):
	print c
else:
	print "-1"


n,bg,ed = map( int,raw_input().split() )
p = map( int,raw_input().split() )
cnt = 0
flag = bg
while flag != ed:
    if cnt and flag == bg:
        cnt = -1
        break
    flag = p[flag-1]
    cnt += 1
print cnt


n,s,t = map(int,raw_input().split())

a = map(int,raw_input().split())

time=0
while(s!=t):
 if time>n:
  print -1
  exit()
 s=a[s-1]
 time+=1

print time


n,s,t=map(int,raw_input().split())
li=map(int,raw_input().split())
if(s!=t):
    f=0
    for i in xrange(n):
        if(li[s-1]==t):
            f=1
            break
        else:
            s=li[s-1]
    if(f==0):
        print "-1"
    if(f==1):
        print i+1
else:
    print "0"


n, s, t = map(int, raw_input().split())

p = map(int, raw_input().split())

v = [False] * len(p)

res = 0
while s != t:
    if v[s - 1]:
        break

    v[s - 1] = True
    s = p[s - 1]
    res += 1

print -1 if s != t else res


def solve(p, s, t):
    def cycle(p):
        res = []
        i = 0
        while i < len(p) and p[i] <= 0: i+=1
        if i >= len(p): return res
        res.append(p[i])
        a = p[p[i]-1]
        while a != res[0]:
            res.append(a)
            a = p[a-1]
        for x in res:
            p[x-1] = -1
        return res

    c = cycle(p)
    while c:
        if s in c and t in c:
            p1, p2 = c.index(s), c.index(t)
            return (p2-p1+len(c))%len(c)
        c = cycle(p)
    return -1

n, s, t = map(int, raw_input().split())
p = map(int, raw_input().split())
print solve(p, s, t)


r=lambda:map(int,raw_input().split())
n,s,t=r()
a=r()
for i in range(n):
    if s==t:print i;exit()
    s=a[s-1]
print -1


n, s, t = map(int, raw_input().split())
p = map(int, raw_input().split())
v, c = [0]*n, 0
while s != t:
    s = p[s-1]
    if v[s-1]:
        print -1
        break
    v[s-1], c = 1, c+1
else:
    print c


#!/usr/bin/env python

import sys

n, start, target = [int(num) for num in sys.stdin.readline().split()]
permutation =  [int(num) for num in sys.stdin.readline().split()]
result = 0
next_position = start
while(next_position != target):
    next_position = permutation[next_position-1]
    result += 1
    if next_position == start:
        result = -1
        break
print result


n, s, t = map(int, raw_input().split())
p = map(int, raw_input().split())
for i in xrange(n):
	if s == t:
		print i
		exit(0)
	else:
		s = p[s-1]
print -1


l=lambda:map(int,raw_input().split())
n,s,t=l()
a=l()
if a[s-1]==t:
    print 1
    exit()
if a[s-1]==s:
    print -1
    exit()
c=1
while True:
    if a[s-1]==t:
        print c
        exit()
    s=a[s-1]
    c+=1
    if c>n:
        print -1
        break


l=lambda:map(int,raw_input().split())
n,s,t=l()
a=l()
if s==t:
    print 0
    exit()
if a[s-1]==t:
    print 1
    exit()
if a[s-1]==s:
    print -1
    exit()
c=1
while True:
    if a[s-1]==t:
        print c
        exit()
    s=a[s-1]
    c+=1
    if c>n:
        print -1
        break


l=lambda:map(int,raw_input().split())
n,s,t=l()
a=l()
if a[s-1]==t:
    print 0
    exit()
if a[s-1]==s:
    print -1
    exit()
c=1
while True:
    if a[s-1]==t:
        print c
        exit()
    s=a[s-1]
    c+=1
    if c>n:
        print -1
        break


I=lambda:map(int,raw_input().split())
n,b,e=I()
a=[0]+I()
cnt,cur=1,a[b]
if b==e: print 0;exit()
while cur!=b:
    if cur==e:
        print cnt
        exit()
    cnt+=1
    cur=a[cur]
print -1


n, s, t = [ int(x) for x in raw_input().strip().split() ]
s -= 1
t -= 1
p = [ int(x) - 1 for x in raw_input().strip().split() ]

mark = [False] * n
ans = 0
while s != t :
    if mark[s] :
        ans = -1
        break
    mark[s] = True
    s = p[s]
    ans += 1
print ans


n,s,t=map(int,raw_input().split())
c=0;
t1=s
d=map(int,raw_input().split())
while(t1!=t and (c==0 or t1!=s)):
    t1=d[t1-1]
    c+=1
if(t1==t):
    print c
else:
    print -1


import sys

data = sys.stdin.readlines()
meta = data[0].strip().split(' ')
jumps = data[1].strip().split(' ')

num = int(meta[0])
start = int(meta[1])
end = int(meta[2])

steps = 0
while start != end:
    start = int(jumps[start - 1])
    if steps > num:
        steps = -1
        break
    steps += 1
print steps


import sys

num_glasses, start, end = [int(i) for i in sys.stdin.readline().split()]
shuffle = [int(i) for i in sys.stdin.readline().split()]

pos = start-1
count = 0
for i in range(num_glasses + 1):
    if pos == end-1:
        break
    else:
        pos = shuffle[pos]-1
        count += 1

if count < num_glasses:
    print count
else:
    print -1


import sys

num_glasses, start, end = [int(i) for i in sys.stdin.readline().split()]
shuffle = [int(i) for i in sys.stdin.readline().split()]

pos = start
count = 0
for i in range(num_glasses + 1):
    if pos == end:
        break
    else:
        pos = shuffle[pos]-1
        count += 1

if count < num_glasses:
    print count
else:
    print -1


import sys

n, s, t = map(int, sys.stdin.readline().split())
shuffle = map(int, sys.stdin.readline().split())

s -= 1
t -= 1
ans = 0
while s != t:
    if shuffle[s] < 0:
        ans = -1
        break
    else:
        tmp = shuffle[s]
        shuffle[s] = -1
        s = tmp - 1
        ans += 1
print ans


line = raw_input()
list = line.split()
n = int(list[0])
s = int(list[1])
t = int(list[2])
line = raw_input()
list = line.split()
p_list = []
was_list = []
for i in range(n):
    p_list.append(int(list[i]))
    was_list.append(0)
was_list[s-1] = 1
result = 0
if s==t:
    print result
else:
    while(1):
        result +=1
        s = p_list[s-1]
        if s==t:
            print result
            break
        if was_list[s-1]==1:
            print -1
            break
        was_list[s-1] = 1


inp=map(lambda x:int(x),raw_input().split())
total,start,end=inp[0],inp[1],inp[2]
state0,state1,count=start,end,0
shuffleparams=map(lambda x:int(x),raw_input().split())
if start==end:
	print 0
else :
	while start!=end:
		start=shuffleparams[start-1]
		if state0==start and count!=0:
			print -1
			break
		if start==end:
			print count+1
			break
		count+=1


[a,b,c]=map(int,raw_input("").strip().split())
d=map(int,raw_input("").strip().split())
b-=1;c-=1
if b==c:
    print "0"
elif d[b]==(b+1) or d[c]==(c+1):
  #  print "y"
    print "-1"
else:
    count=0
    t={}
    j=0
    for i in xrange(1,a+1):
        t[i]=d[j]
        j+=1
    #print t
    l=[];b+=1;c+=1
    l.append(b)
    i=b
    while 1:
        i=t[i]
        #print "iii",i
        if i not in l:
            #print i,"ha"
            l.append(i)
            count+=1
        else:
            #print i,"lal"
            print "-1"
            break
        if i==c:
            print count
            break


[a,b,c]=map(int,raw_input("").strip().split())
d=map(int,raw_input("").strip().split())
b-=1;c-=1
if b==c:
    print "0"
elif d[b]==(b+1) or d[c]==(c+1):
    print "-1"
else:
    count=0
    t={}
    j=0
    for i in xrange(1,a+1):
        t[i]=d[j]
        j+=1
    l={};b+=1;c+=1
    for i in xrange(a+1):
        l[i]=0
    l[b]=1
    i=b
    while 1:
        i=t[i]
        if l[i]==0:
            l[i]=1
            count+=1
        else:
            print "-1"
            break
        if i==c:
            print count
            break


n,s,t=map(int,raw_input().split())
check=map(int,raw_input().split())
L=[];s-=1;t-=1;d={};c=0
for i in xrange(n):d[i]=check[i]-1
for i in xrange(n):
    if s==t:print c;break
    s=d[s];c+=1
else:print -1


n,s,t=map(int,raw_input().split())
check=map(int,raw_input().split())
L=[];s-=1;t-=1;d={}
for i in xrange(n):d[i]=check[i]-1
c=0
while s<>t:
    if s not in L:L.append(s)
    else:print -1;break
    s=d[s];c+=1
else:print c


r=lambda:map(int,raw_input().split())
n,s,t=r()
a=r()
for i in range(n):
    if s==t:print i;exit()
    s=a[s-1]
print -1


def movements(n,s,e,movements):
    seq=0
    currIndex=s-1
    while(currIndex!=e-1):
        to=movements[currIndex]
        currIndex=to-1
        seq+=1
        if(seq>n):return -1
    return seq

n,s, e = [int(j) for j in raw_input().split()]
movs=[int(j) for j in raw_input().split()]
print movements(n,s,e,movs)


[n, s, t] = map (int, raw_input().split());
p = map (int, raw_input().split());
st = [False] * n;
cur = s; ans = 0;
while s != t and (not st[s-1]):
    st[s-1] = True;
    s = p[s-1];
    ans += 1

if s != t:
    print -1
else:
    print ans


import sys
args = map(int, raw_input().split())
n = args[0]
const_s = args[1]
t = args[2]
cups = map(int, raw_input().split())
#print cups
count = 0
s = const_s
while s != t:
	s = cups[s-1]
	if s == const_s:
		print '-1'
		exit(0)
	count += 1

print count


import sys, math
def rs():
    return sys.stdin.readline().strip()
def ri():
    return int(sys.stdin.readline().strip())
def ras():
    return sys.stdin.readline().strip().split()
def rai():
    return map(int,sys.stdin.readline().strip().split())

n,s,t = rai()
v = [False]*(n+1)
p = [0]+rai()
n = 0;
while s != t and (not v[s]):
    v[s] = True
    s = p[s]
    n += 1;
if s != t: print -1
else: print n


n,s,t=raw_input().split()
n=int(n)
s=int(s)
t=int(t)
ls=[int(x) for x in raw_input().split()]
count=0
if s==t:
	print('0')
elif ls[t-1]!=t:
	while ls[s-1]!=t:
		s=ls[s-1]
		count+=1
	print(count+1)
else:
	print('-1')


n,s,t=raw_input().split()
n=int(n)
s=int(s)
t=int(t)
ls=[int(x) for x in raw_input().split()]
count=0
if s==t:
	print('0')
elif ls[t-1]!=t:
	while ls[s-1]!=t and ls[s-1]!=0 :
		s=ls[s-1]
		ls[s-1]=0
		count+=1
	if ls[s-1]==0:
		print('-1')
	else:
		print(count+1)
else:
	print('-1')


n,s,t=raw_input().split()
n=int(n)
s=int(s)
t=int(t)
ls=[int(x) for x in raw_input().split()]
count=0
if s==t:
	print('0')
elif ls[t-1]!=t:
	while s!=t and ls[s-1]!=0 :
		temp=ls[s-1]
		ls[s-1]=0
		s=temp
		count+=1
	if ls[s-1]==0:
		print('-1')
	else:
		print(count)
else:
	print('-1')


n,s,t=raw_input().split()
n=int(n)
s=int(s)
t=int(t)
ls=[int(x) for x in raw_input().split()]
ls1=sorted(ls)
i=0
i1=0
for x in range(n):
	if ls[x]==ls1[s-1]:
		i=x
	if ls[x]==ls1[t-1]:
		i1=x
if s<=t:
	print(i-i1)
else:
	print(i1-i)


__author__ = 'robert'

def solve():
    from sys import stdin
    data = [map(int, line.split()) for line in stdin]
    n, s, t = data[0]
    perm = data[1]
    pos = s
    moves = 0
    while True:
        if pos == t:
            break
        pos = perm[pos - 1]
        moves += 1
        if pos == s:
            break
    if pos == t:
        print moves
    else:
        print -1

solve()


#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
    int m,n,t;
    cin>>t;
    while(t!=0)
    {
        cin<<n;
        cin<<m;
        if(n==1)
        {
            cout<<0;
        }
        else if(n==2)
        {
            cout<<m;
        }
        else
        {
           cout<<(m*2);
        }
        t--;
    }
}


#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
    int m,n,t;
    cin>>t;
    while(t!=0)
    {
        cin>>n;
        cin>>m;
        if(n==1)
        {
            cout<<0;
        }
        else if(n==2)
        {
            cout<<m;
        }
        else
        {
           cout<<(m*2);
        }
        t--;
    }
}


#include<stdio.h>
#include <iostream.h>
using namespace std;
int main()
{
    int m,n,t;
    cin>>t;
    while(t!=0)
    {
        cin<<n;
        cin<<m;
        if(n==1)
        {
            cout<<0;
        }
        else if(n==2)
        {
            cout<<m;
        }
        else
        {
           cout<<(m*2);
        }
        t--;
    }
}


#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
    int m,n,t;
    cin>>t;
    while(t!=0)
    {
        cin>>n;
        cin>>m;
        if(n==1)
        {
            cout<<0<<endl;
        }
        else if(n==2)
        {
            cout<<m<<endl;
        }
        else
        {
           cout<<(m*2)<<endl;
        }
        t--;
    }
}


/*#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string.h>
#include<stack>
#include<cmath>
using namespace std;
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n,k,an[100],bn[100];
        scanf("%d%d",&n,&k);
        for(int i=0;i<n;i++)
            scanf("%d",&an[i]);
        for(int i=0;i<n;i++)
            scanf("%d",&bn[i]);
        sort(an,an+n);
        sort(bn,bn+n);
        for(int i=0;i<k;i++){
            if(an[i]<bn[n-i-1])
               swap(an[i],bn[n-i-1]);
        }
        int sum=0;
        for(int i=0;i<n;i++){
            //printf("i=%d an=%d bn=%d\n",i,an[i],bn[i]);
            sum+=an[i];
        }
        printf("%d\n",sum);
    }
    return 0;
}*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
int main(){
	int t,n,m;
	cin>>t;
	while(t--){
        scanf("%d%d",&n,&m);
		if(n==1)
			printf("0\n");
		else if(n==2)
		    printf("%d\n",m);
		else
		    printf("%d\n",m*2);
	}
	return 0;
}


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

using namespace std;

int main() {

   int n;
   int in;
   cin >> n;

   vector <int> team;

   for (int i = 0; i < n*2; i++)
	   {
	   cin >> in; team.push_back(in);
	   }

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

	   if (i%2==0)
		   {
		   if(team[i]==1) cout << 0 << endl;

		   else if(team[i]==2) cout << team[i+1] << endl;

		   else cout << team[i+1]*2 << endl ;

		   }
	   }

   }


#include <iostream>
#include <vector>
using namespace std;
//problem A. most unstabled array #632
int main() {
  int testCases = 0;
  cin >> testCases;
  vector<int> vect;
  for(int i = 0;i<testCases;i++){
    int n;
    int m;
    cin >> n >> m;
    if(n ==1){
      vect.push_back(0);
    }
    else if( n ==2){
      vect.push_back(m);
    }
    else
    vect.push_back(2*m);
  }
  for(int j = 0;j<testCases;j++){
    cout << vect[j]<<endl;
  }
}


#include <iostream>

using namespace std;

int main() {

    int t, sum, n;
    cin >> t;

    while (t-- > 0) {
        cin >> n >> sum;
        if (n == 1)
            cout << 0 << endl;
        if (n == 2)
            cout << sum << endl;
        if (n > 2)
            cout << 2 * sum << endl;
    }

    return 0;
}


#include<iostream>
using namespace std;

int main()
{
	int iterations = 0;
	cin >> iterations;
	int a = 0, b = 0;
	while (iterations--)
	{
		cin >> a >> b;
		if (a == 1)
		{
			cout << 0 << endl;
		}
		else if (a == 2)
		{
			cout << b << endl;
		}
		else if (a == b)
		{
			cout << 2 * a << endl;
		}

	}

	return 0;
}


#include<iostream>
using namespace std;

int main()
{
	int iterations = 0;
	cin >> iterations;
	int a = 0, b = 0;
	while (iterations--)
	{
		cin >> a >> b;
		if (a == 1)
		{
			cout << 0 << endl;
		}
		else if (a == 2)
		{
			cout << b << endl;
		}
		else
		{
			cout << 2 * a << endl;
		}

	}

	return 0;
}


#include<iostream>
using namespace std;

int main()
{
	int iterations = 0;
	cin >> iterations;
	int a = 0, b = 0;
	while (iterations--)
	{
		cin >> a >> b;
		if (a == 1)
		{
			cout << 0 << endl;
		}
		else if (a == 2)
		{
			cout << b << endl;
		}
		else
		{
			cout << 2 * b << endl;
		}

	}

	return 0;
}


/* Task description
https://codeforces.com/problemset/problem/1353/A
*/

#include <iostream>

int main()
{
	int cases;
	long length, sum;
	std::cin >> cases;

	for (int i = 0; i < cases; ++i)
	{
		std::cin >> length >> sum;

		switch (length)
		{
		case 1:		std::cout << 0;			break;
		case 2:		std::cout << sum;		break;
		default:	std::cout << 2 * sum;	break;
		}
		std::cout << std::endl;
	}
}


#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
	int n, t, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 1)
			cout << 0 << endl;
		else if (n == 2)
			cout << m << endl;
		else
			cout << m * 2 << endl;
	}
}


#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
	int n, t, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n = 1)
			cout << 0 << endl;
		else if (n = 2)
			cout << 1 << endl;
		else
			cout << n * 2 << endl;
	}
}


#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
	int n, t, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 1)
			cout << 0 << endl;
		else if (n == 2)
			cout << 1 << endl;
		else
			cout << n * 2 << endl;
	}
}


#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
	int n, t, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 1)
			cout << 0 << endl;
		else if (n == 2)
			cout << n << endl;
		else
			cout << n * 2 << endl;
	}
}


#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
	int n, t, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n = 1)
			cout << 0;
		else if (n = 2)
			cout << 1;
		else
			cout << n * 2;
	}
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>

using namespace std;

int main()
{
	int t, n, m;
	float x, a;
	cin >> t;
	while (t--)
	{
		cin >> n >> m;
		if (n == 1)
		{
			cout << "0" << "\n";
		}
		else if (n == 2)
		{
			cout << m << "\n";
		}
		else
		{
			cout << 2 * m << "\n";
		}
	}
	return 0;
}


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

using namespace std;

int main() {

	int t;
	cin >> t;
	while (t--) {
		long long n, m;
		cin >> n >> m;
		if (n == 1) {
			cout << 0 << endl;
		} else if (n == 2) {
			cout << m << endl;
		} else {
			cout << m * 2 << endl;
		}
	}

	return 0;
}


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

using namespace std;

int main() {

	int x, index = 1;
	cin >> x;
	x--;
	while (x > 0) {
		x -= pow(2, index) - pow(2, index -1);
	}
	cout << x + 1;

	return 0;
}


using namespace std;
#include<iostream>

int NumTestCases = 0;

int main() {
	int size = 0;
	int sum = 0;
	cin >> NumTestCases;
	int ans = 0;
	for (int i = 0;i < NumTestCases;i++)
	{
		cin >> size >> sum;
		if (size == 1) ans = 0;
		else if (size == 2) ans=sum;
		else ans = 2 * sum;
		cout << ans<<endl;
	}
	return 0;
}


using namespace std;
#include<iostream>

int NumTestCases = 0;

int main() {
	int size = 0;
	int sum = 0;
	cin >> NumTestCases;
	int ans = 0;
	for (int i = 0;i < NumTestCases;i++)
	{
		cin >> size >> sum;
		if (size == 1) {
			cout << 0 << endl;
			continue;
		}
		int NumElem = size/2;
		int val = sum / NumElem;
		if (size % 2 == 0) {
			if (size == 2)
				ans = sum;
			else if (sum == 1)
				ans = 2;
			else
				ans = val*4+2 * (NumElem - 2)*val;
		}
		else {
			ans = 2 * ((sum/NumElem)*(NumElem-1))+2*(sum%NumElem+sum/NumElem);
		}
		cout << ans<<endl;
	}
	return 0;
}


#include <iostream>
using namespace std;

int main()
{
	int testCases;
	int n;
	int sum;

	cin >> testCases;

	while (testCases != 0)
	{
		cin >> n >> sum;
		if (n == 1)
		{
			cout << 0 << endl;
		}
		else if (n == 2)
		{
			cout << sum << endl;
		}
		else
		{
			cout << 2 * sum << endl;
		}
		testCases--;
	}

	return 0;
}


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

#define min(a,b) (a<b)?a:b

/*int abs(int x) {
	return (x > 0) ? x : -x;
}*/

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

	while (N--) {
		int m, n;
		cin >> n >> m;

		if (n == 1) {
			cout <<0<< endl;
		}
		else if(n==2)
		{
			cout << m << endl;
		}
		else{

			cout << m*2 << endl;
		}
	}

	return 0;
}


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

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

	while (--N) {
		int m, n;
		cin >> n >> m;

		vector<int> arr(n, 0);

		arr.at(3) = m;
		int sum = 0;

		for (int i = 0; i < n; i++)
		{
			sum += arr[i];
			if (n >= 3)
				break;
		}

		cout << sum;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main()
{
	// your code goes here
	int t,n,m,b,i;
	cin>>t;
	while(t--)
	{
	  b=0;
	  cin>>n>>m;
	  if(n>2)
	  {
	       b=n+m;
	       cout<<b<<endl;
	  }
	  else if(n==2)
	  {
	      cout<<m<<endl;

	  }
	  else
	  cout<<'0'<<endl;
	}
	 return 0;
}


#include <iostream>
using namespace std;

int main()
{
	// your code goes here
	int t,n,m,b,i;
	cin>>t;
	while(t--)
	{
	  b=0;
	  cin>>n>>m;
	  if(n>2)
	  {
	       b=2*m;
	       cout<<b<<endl;
	  }
	  else if(n==2)
	  {
	      cout<<m<<endl;

	  }
	  else
	  cout<<'0'<<endl;
	}
	 return 0;
}


#include <iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
void solve()
{
	int n; int a;
	cin >> n >> a;
	if (n == 1)
	{
		cout << 0 << endl;
		return;
	}
	if (n == 2)
	{
		cout << a << endl;
		return;
	}
	if (n > 2)
	{
		cout << a*2 << endl;
		return;
	}
}

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


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

int main()
{
    long long int t,n,m,a,b,c,d,e;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>m;
        if(n==1){cout<<0;}
        else{ a=n/2;
              b=m/a;
              c=m-((m/a)*(a-1));
              if(n%2==0){
                          d=(b>c)?b:c;
                          e=2*d+(a-2)*b;
                          cout<<e;
              }
              else{ cout<<2*c+(a-1)*b;}

        }
    }

   return 0;
}


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

int main()
{
    long long int t,n,k;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>k;
        if(n==1){cout<<0;}
        else if(n==2){cout<<k;}
        else{cout<<2*k;}
    }

   return 0;
}


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

int main()
{
    long long int t,n,m,a,b,c,d,e;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>m;
        if(n==1){cout<<0;}
        else{ a=n/2;
              b=m/a;
              c=m-((m/a)*(a-1));
              if(n%2==0){
                          d=(b>c)?b:c;
                          e=2*d+(a-2)*b;
                          cout<<e;
              }
              else{ cout<<2*c+(a-1)*b;}

        }
    }

   return 0;
}


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

int main()
{
    long long int t,n,k;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>k;
        if(n==1){cout<<0;}
        else if(n==2){cout<<k;}
        else{cout<<2*k;}
    }

   return 0;
}
→Judgemen


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

int main()
{
    long long int t,n,k;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>k;
        if(n==1){cout<<0<<endl;}
        else if(n==2){cout<<k<<endl;}
        else{cout<<2*k<<endl;}
    }

   return 0;
}


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

int main()
{
    long long int t,n,m,a,b,c,d,e;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>m;
        if(n==1){cout<<0<<endl;}
        else{ a=n/2;
              b=m/a;
              c=m-((m/a)*(a-1));
              if(n%2==0){
                          d=(b>c)?b:c;
                          e=2*d+(a-2)*b;
                          cout<<e<<endl;
              }
              else{ cout<<2*c+(a-1)*b<<endl;}

        }
    }

   return 0;
}


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

int main()
{
    long long int t,n,m,a,b,c,d,e;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>m;
        if(n==1){cout<<0<<endl;}
        else{ a=n/2;
              b=m/a;
              c=m-((m/a)*(a-1));
              if(n%2==0){
                          d=(b>c)?b:c;
                          e=2*d+(a-2)*b;
                          cout<<e<<endl;
              }
              else{ cout<<2*c+(a-1)*b*2<<endl;}

        }
    }

   return 0;
}


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

int main()
{
    long long int t,n,m,a,b,c,d,e;
    cin>>t;
    for(long long int i=0;i<t;i++)
    {
        cin>>n>>m;
        if(n==1){cout<<0<<endl;}
        else{ a=n/2;
              b=m/a;
              c=m-((m/a)*(a-1));
              if(n%2==0){
                          d=(b>c)?b:c;
                          e=2*d+(a-2)*b*2+b;
                          cout<<e<<endl;
              }
              else{ cout<<2*c+(a-1)*b*2<<endl;}

        }
    }

   return 0;
}


#include <iostream>
#include <string>

using namespace std;

int main() {
	int t;
	int n[1000], m[1000];
	cin >> t;
	for (int i = 0; i < t; i++) cin >> n[i] >> m[i];

	for (int i = 0; i < t; i++) {
		if (n[i] == 2) cout << m[i] << endl;
		else
			if (n[i] == 1) cout << 0 << endl;
			else cout << m[i] * 2 << endl;
	}

}


#include <iostream>
#include <string>

using namespace std;

int min(int x, int y) {
	if (x < y) return x;
	else return y;
}

int main() {
	int t;
	cin >> t;
	while (t--) {
		int n, m;
		cin >> n >> m;
		cout << min(2, n - 1) * m << endl;
	}

	return 0;

}


#include <iostream>
#include <string>

using namespace std;

int main() {
	int t;
	unsigned long n[1000], m[1000];
	cin >> t;
	for (int i = 0; i < t; i++) cin >> n[i] >> m[i];

	for (int i = 0; i < t; i++) {
		if (n[i] == 2) cout << m[i] << endl;
		else
			if (n[i] == 1) cout << 0 << endl;
			else cout << m[i] * 2 << endl;
	}

}


#include <iostream>
#include <string>

using namespace std;

int main() {
	int t;
	int n[1000], m[1000];
	cin >> t;
	for (int i = 0; i < t; i++) cin >> n[i] >> m[i];

	for (int i = 0; i < t; i++) {
		if (n[i] == 2) cout << m[i] << endl;
		else
			if (n[i] == 1) cout << 0 << endl;
			else cout << m[i] * 2 << endl;

	}

}


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

int main() {
	int t;
	cin>>t;
	while(t--){
	    int n,k;
	    cin>>n>>k;
	    int *a=new int[n+1];
	    for(int i=1;i<=n;i++){
	        cin>>a[i];
	    }
	    int *b=new int[n+1];
	    for(int i=1;i<=n;i++){
	        cin>>b[i];
	    }
	    sort(b+1,b+n+1);
	    sort(a+1,a+n+1);
	    for(int i=1;i<=k;i++){
	        if(a[i]<b[n+1-i]){
	        a[i]=b[n+1-i];
	        }
	        else{
	            break;
	        }
	    }
	    int sum=0;
	    for(int i=1;i<=n;i++){
	        sum+=a[i];
	    }
	    cout<<sum<<endl;
	}
	return 0;
}


#include <iostream>
using namespace std;
int ans(int n,int m){
    if(n==1) return 0;
    if(n==2) return m;
    if(n>2) return 2*m;
}
int main() {
	int t;
	cin>>t;
	while(t--){
	    int n,m;
	    cin>>n>>m;
	    cout<<ans(n,m)<<endl;
	}
	return 0;
}


#include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
long    int m,n;

    int i,j;
    for(i=0;i<t;i++)
    {
    cin>>m>>n;
    if(m==1)
    {
        cout<<0<<"\n";
        continue;
    }
    else if(m%2==0)
    {
        cout<<n<<"\n";
    }
    else
    cout<<2*n<<"\n";
    }

}


#include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
long    int m,n;

    int i,j;
    for(i=0;i<t;i++)
    {
    cin>>m>>n;
    if(m==1)
    {
        cout<<0<<"\n";
        continue;
    }
    else if(m==2)
    {
        cout<<n<<"\n";
    }
    else
    cout<<2*n<<"\n";
    }

}


#include <iostream>

using namespace std;

int main()
{
    int t;
    cin>>t;
    int n[10005],m[10005];

    for(int i=0;i<t;i++)
    {
        cin>>n[i]>>m[i];
    }

    for(int i=0;i<t;i++)
    {
        if(n[i]==1)
        {
            cout<<0<<endl;
        }
        else if(n[i]==2)
        {
            cout<<m[i]<<endl;
        }
        else if(n[i]>2)
        {
            cout<<2*m[i]<<endl;
        }
    }

    return 0;
}


#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;

int main(void)
{
    int T;
    scanf("%d", &T);
    while(T -- )
    {
        int n, sum;
        scanf("%d%d", &n, &sum);
        if(n == 2) printf("%d\n", sum);
        else if(n == 1) printf("0\n");
        else if(n % 2 == 0 || n & 1) printf("%d\n", n * 2);
    }
}


#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;

int main(void)
{
    int T;
    scanf("%d", &T);
    while(T -- )
    {
        int n, sum;
        scanf("%d%d", &n, &sum);
        if(n == 2) printf("%d\n", sum);
        else if(n == 1) printf("0\n");
        else if(n % 2 == 0 || n & 1) printf("%d\n", sum * 2);
    }
}


// CodeforcesGameSolution.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

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

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

using namespace std;

//void printPlayer1()
//{
//	cout << "Ashishgup" << endl;
//}
//
//void printPlayer2() {
//	cout << "FastestFinger" << endl;
//}
//
//bool checkPrime(int n)
//{
//	int nN = min(maxN, n);
//	for (int i = 2; i < nN; i++)
//	{
//		if (n % i == 0)
//			return false;
//	}
//	return true;
//}

//bool CMP(int a, int b)
//{
//	return a > b;
//}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, m;
		cin >> n >> m;
		if (n == 1)
		{
			cout << 0 << endl;
		}
		else if (n == 2)
		{
			cout << m << endl;
		}
		else {
			cout << m * 2 << endl;
		}

	}
}


#include <iostream>
#include <fstream>
#include <istream>
#include <stdio.h>
#include <stdlib.h>
#include <unordered_map>
#include <vector>
#include <math.h>
#include <string>
#include <algorithm>
#include <math.h>
#include <set>
#include<queue>
#define ll long long
#define mp(x,y) make_pair(x,y)
#define read(x) cin>>x;
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define yes "YES"
#define no "NO"
#define alice "Alice"
#define bob "Bob"
using namespace std;

int main(){
	int T;
	read(T);
	while(T--){
		ll n , m;
		cin>>n>>m;
		if(n > 2){
			cout<<m*2<<endl;
		}else if (n == 1){
			cout<<0<<endl;
		}else{
			cout<<m<<endl;
		}
	}
}


#include <iostream>
using namespace std;
int main()
{
    long long int t,n,m;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        if(n==1)
        {
            cout<<0<<endl;
        }
        if(n==2){ cout<<m<<endl;}
        if(n>=3) { cout<< (2*m)<<endl;}
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long int t,n,m;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        if(n==1)
        {
            cout<<0<<endl;
        }
        if(n==2){ cout<<m<<endl;}
        if(n>=3) { cout<< (2*m)<<endl;}
    }
    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int a, b, c;
    cin >> a;
    while(a--){
        cin >> b >> c;
        if(b == 1){
            cout << 0 << endl;
        }else if(b == 2 || b == 3){
            cout << c << endl;
        }else if(b == 4){
            cout << c * 2 - 1 << endl;
        }else{
            cout << c * 2 << endl;
        }
    }
    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int a, b, c;
    cin >> a;
    while(a--){
        cin >> b >> c;
        if(b == 1){
            cout << 0 << endl;
        }else if(b == 2){
            cout << c << endl;
        }else{
            cout << c * 2 << endl;
        }
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;

        if(n==1) cout<<0<<"\n";
        else if(n==2) cout<<m<<"\n";
        else{
            cout<<m*2<<"\n";

        }

    }
}


#include <iostream>

using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;

        if(n==1) cout<<0<<"\n";
        else if(n==2) cout<<m<<"\n";
        else{
            cout<<m*2<<"\n";

        }

    }
}


#include<iostream>
using namespace std;
int main() {
	int t;
	scanf("%d", &t);
	for (int i = 0; i < t; i++)
	{
		int a, b;
		scanf("%d%d", &a, &b);

		if(a % 2 == 1){
			int len = a / 2;
			int sum = 0;

			if (len == 0) {
				printf("0\n");
				continue;
			}

			for (int i = 0; i < len - 1; i++)
			{
				sum += 1 * 2;
			}
			sum += (b - (len - 1)) * 2;

			printf("%d\n", sum);
		}
		else {
			int len = a / 2;
			int sum = 0;

			if (len == 1) {
				printf("%d\n", b);
				continue;
			}

			int tmp = b / (len - 1);
			for (int i = 0; i < len-1; i++)
			{
				if (i == len-2) tmp = b;
				sum += (tmp * 2);
				b -= tmp;
			}

			printf("%d\n", sum);
		}
	}
}


#include<iostream>
using namespace std;
int main() {
	int t;
	scanf("%d", &t);
	for (int i = 0; i < t; i++)
	{
		int a, b;
		scanf("%d%d", &a, &b);

		if(a % 2 == 1){
			int len = a / 2;
			int sum = 0;

			if (len == 0) {
				printf("0\n");
				continue;
			}

			sum += 2 * (len - 1);
			sum += (b - (len - 1)) * 2;

			printf("%d\n", sum);
		}
		else {
			int len = a / 2;
			int sum = 0;

			if (len == 1) {
				printf("%d\n", b);
				continue;
			}

			int tmp = b / (len - 1);

			sum += (tmp * 2)*(len - 2);
			b = b - (tmp * (len - 2));
			sum += b * 2;

			printf("%d\n", sum);
		}
	}
}


#include<bits/stdc++.h>
using namespace std;
int main() {
	int t;
	scanf("%d", &t);
	for (int i = 0; i < t; i++)
	{
		int a, b;
		scanf("%d%d", &a, &b);

		if(a % 2 == 1){
			int len = a / 2;
			int sum = 0;

			if (len == 0) {
				printf("0\n");
				continue;
			}

			for (int i = 0; i < len - 1; i++)
			{
				sum += 1 * 2;
			}
			sum += (b - (len - 1)) * 2;

			printf("%d\n", sum);
		}
		else {
			int len = a / 2;
			int sum = 0;

			if (len == 1) {
				printf("%d\n", b);
				continue;
			}

			int tmp = b / (len - 1);
			for (int i = 0; i < len-1; i++)
			{
				if (i == len-2) tmp = b;
				sum += (tmp * 2);
				b -= tmp;
			}

			printf("%d\n", sum);
		}
	}
}


#include <iostream>
#include <math.h>
#include <algorithm>
#include <vector>
#define ll long long
using namespace std;

int main()
{
    ll t;
     // n len mas, m sum mas
    cin >> t;
    while(t != 0){
        ll n, m;
        cin >> n >> m;
        if(n == 1) cout << 0 << endl;
        else if(n == 2) cout << m << endl;
        else cout << m * 2 << endl;
        t--;
    }

}


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

using namespace std;

int div_up(int x, int y) {
	return (x - 1) / y + 1;
}

int main() {

	int t, n, m;
	cin >> t;

	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		cout << (n - 1) / (div_up((n - 1) , 2)) * m << endl;
	}

	return 0;
}


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

using namespace std;

int div_up(int x, int y) {
	return (x - 1) / y + 1;
}

int main() {

	int t, n, m;
	cin >> t;

	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 2) {
			cout << m << endl;
		}
		else {
			if (n % 2 == 0) {
				n = n - 1;
				cout << (n - 1) / (div_up((n - 1), 2)) * m << endl;
			}
			else {
				cout << (n - 1) / (div_up((n - 1), 2)) * m << endl;
			}
		}

	}

	return 0;
}


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

using namespace std;

int div_up(int x, int y) {
	return (x - 1) / y + 1;
}

int main() {

	int t, n, m;
	cin >> t;

	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 2) {
			cout << m;
		}
		else {
			if (n % 2 == 0) {
				n = n - 1;
				cout << (n - 1) / (div_up((n - 1), 2)) * m << endl;
			}
			else {
				cout << (n - 1) / (div_up((n - 1), 2)) * m << endl;
			}
		}

	}

	return 0;
}


//#include "pch.h"
#include <iostream>
using namespace std;

int main()
{
	int t, n, m;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		if (n == 1)
			cout << 0 << endl;
		else
			if (n == 2)
				cout << m << endl;
			else
				if (n > 2)
					cout << 2 * m << endl;
	}

}


#include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
        if(n==1)
        cout<<0<<endl;
        else if(n==2)
        cout<<m<<endl;
        else if(n%2==1)
        cout<<2*m<<endl;
        else
        cout<<m<<endl;
    }
    return 0;
}


#include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
        if(n-1>2)
        cout<<2*m<<endl;
        else
        cout<<(n-1)*m<<endl;
    }
}


#include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
        if(n==1)
        cout<<0<<endl;
        else if(n==2)
        cout<<m<<endl;
        else if(n%2==1)
        cout<<2*m<<endl;
        else
        cout<<2*m-1<<endl;
    }
    return 0;
}


#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>

using namespace std;

int solve() {
    int n;

    cin >> n;

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

        cin >> b >> c;

        if ( b == 1 ) {
            cout << 0 << endl;
        } else if ( b == 2 ) {
            cout << c << endl;
        } else {
            cout << c * 2 << endl;
        }
    }

    return 0;
};

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


#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>

using namespace std;

int solve() {
    int n;

    cin >> n;

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

        cin >> b >> c;

        if ( b == 1 ) {
            cout << 0 << endl;
        } else if ( b == 2 ) {
            cout << c << endl;
        } else {
            cout << c * 2 << endl;
        }
    }
};

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


#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int t;
	int n, m;
	int i;
	vector <int> a;

	cin >> t;

	for(i = 0; i < t; i++)
	{
		cin >> n >> m;
		if(n == 1)
		{
			a.push_back(0);
		}
		else if(n == 2)
		{
			a.push_back(m);
		}
		else
		{
			a.push_back(m*=2);
		}
	}

	for(i = 0; i < t; i++)
	{
		cout << a[i] << endl;
	}
}


#include <bits/stdc++.h>

using namespace std;

vector <int> a;

int main()
{
	int t;
	int n, m;
	int i;

	cin >> t;

	for(i = 0; i < t; i++)
	{
		cin >> n >> m;
		if(n == 1)
		{
			a.push_back(0);
		}
		else if(n == 2)
		{
			a.push_back(m);
		}
		else
		{
			a.push_back(m*=2);
		}
	}

	for(i = 0; i < t; i++)
	{
		cout << a[i] << endl;
	}
}


//sliding window
#include<iostream>
using namespace std;
#include<string>
#define ll long long
#include<algorithm>
#include<vector>
#include<map>
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		ll int n,m;
		cin>>n>>m;
		if(n==2)
		cout<<m<<endl;
		else if(n==1)
		cout<<0<<endl;
		else
		cout<<2*m<<endl;
	}}


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <algorithm>
#include <set>
#include <functional>
#include <numeric>
#include <iterator>
#include <iomanip>
#define ll long long
const int mod = 1e9 + 7;
using namespace std;

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, m;
		cin >> n >> m;
		if (n < 3)
			cout << (n == 1 ? 0 : m) << endl;
		else
			cout << 2 * m << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <algorithm>
#include <set>
#include <functional>
#include <numeric>
#include <iterator>
#include <iomanip>
#define ll long long
const int mod = 1e9 + 7;
using namespace std;

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, m;
		cin >> n >> m;
		if (n < 3)
			cout << (n == 1 ? 0 : n) << endl;
		else
			cout << 2 * n << endl;
	}
	return 0;
}