#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <bitset>
#include <cassert>
#include <time.h>
#include <numeric>

using namespace std;
 
#define int long long
#define pb push_back
#define in insert
#define F first
#define S second
#define mod 1000000007
#define endl '\n'
#define test(x) int x;cin>>x; while(x-->0)
#define debug(x) cout << "[ " << #x  << " : " << x << " ]" << endl;
void fast_io()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("error.txt", "w", stderr);
	freopen("output.txt", "w", stdout);
#endif
}
void sol()
{
    int n; cin>>n;
    int arr[n],brr[n],amin=100001,bmin=100001;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i]>>brr[i];
        amin=min(amin,arr[i]); 
        bmin=min(bmin,brr[i]);
    }
    //cout<<amin<<" "<<bmin<<" ";
    int f=0;
    for(int i=0;i<n;i++)
    {
        if(arr[i]==amin and brr[i]==bmin)
            f=1;
    }
    if(f==1)
    {
       sort(arr,arr+n);
       sort(brr,brr+n);
       int ans1=amin+bmin;
       int ans2=min(max(arr[0],brr[1]),max(arr[1],brr[0]));
       cout<<min(ans1,ans2);
    }
    else
        cout<<max(amin,bmin);


}

int32_t main()
{
	fast_io();
	//test(t)
	sol();
	//cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	//cerr << sizeof(dp)*(1e-6) << " megabytes\n";
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define elif else if
#define sp(x) fixed << setprecision(x)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using ll = long long;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const int MOD = 1000000007;
//const int MOD = 998244353;
const int inf = (1<<30)-1;
const ll INF = (1LL<<60)-1;
const double pi = acos(-1.0);
const double EPS = 1e-10;
template<typename T> bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;};
template<typename T> bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;};

int main(){
    int T;
    cin >> T;
    while(T--){
        string S;
        cin >> S;
        if(S > "atcoder") {cout << 0 << endl; continue;}
        int ptr = 0;
        int N = sz(S);
        while(ptr < N && S[ptr] == 'a') ptr++;
        if(ptr == N) {cout << -1 << endl; continue;}
        int cnt = 0;
        while(S <= "atcoder"){
            swap(S[ptr-1], S[ptr]);
            ptr--, cnt++;
        }
        cout << cnt << endl;
    }
}