#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define REP(i,n) for (int i = 1; i < (int)(n); i++)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define debug(var) do{cout << #var << " : "; view(var);}while(0)
template<class T> bool chmin(T &a, T b) {if(a>b) {a=b;return 1;}return 0;}
template<class T> bool chmax(T &a, T b) {if(a<b) {a=b;return 1;}return 0;}
using namespace std;
template<class T> void view(T e) {cout << e << endl;}
template<class T> void view(const vector<T> &v) {for(const auto &e : v){cout << e << " ";} cout << endl;}
template<class T> void view(const vector<vector<T>> &vv) {for(const auto &v : vv){view(v);}}
using vint = vector<int>;
using vvint = vector<vector<int>>;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<int,int>;
const int inf = 1<<30;
const ll inf_l = 1LL<<61;
const int MAX = 1e5;

vint dx = {1, 0, -1, 0};
vint dy = {0, 1, 0, -1};

int h, w;
vector<string> field;
P start, goal;
int d[2005][2005];
vector<vector<P>> warp(26);

int to_int(P p) {
    return p.first * w + p.second;
}

P to_cood(int x) {
    return P(x / w, x % w);
}

void solve(P p) {
    priority_queue<P, vector<P>, greater<P>> q;
    q.push(P(0, to_int(p)));
    while (!q.empty()) {
        P p = q.top(); q.pop();
        int x = to_cood(p.second).second;
        int y = to_cood(p.second).first;
        if (d[y][x] < p.first) continue;
        d[y][x] = p.first;
        if ('a' <= field[y][x] && field[y][x] <= 'z') {
            vector<P> &w = warp[field[y][x] - 'a'];
            auto ptr = w.begin();
            while (ptr != w.end()) {
                if (d[(*ptr).first][(*ptr).second] > p.first + 1) {
                    d[(*ptr).first][(*ptr).second] = p.first + 1;
                    q.push(P(p.first + 1, to_int(*ptr)));
                    ptr++;
                } else ptr = w.erase(ptr);
            }
        }
        rep(i,4) {
            int n_x = x + dx[i];
            int n_y = y + dy[i];
            if (n_x >= 0 && n_x < w && n_y >= 0 && n_y < h) {
                if (field[n_y][n_x] == '#') continue;
                if (d[n_y][n_x] > p.first + 1) {
                    d[n_y][n_x] = p.first + 1;
                    q.push(P(p.first + 1, to_int(P(n_y, n_x))));
                }
            }
        }
    }
}

int main() {
    cin >> h >> w;
    field.resize(h);
    rep(i,h) cin >> field[i];
    rep(i,h)rep(j,w) {
        if (field[i][j] == 'S') start = P(i, j);
        if (field[i][j] == 'G') goal = P(i, j);
        if ('a' <= field[i][j] && field[i][j] <= 'z') {
            warp[field[i][j] - 'a'].push_back(P(i, j));
        }
    }
    rep(i,h)rep(j,w) d[i][j] = inf;
    solve(start);
    // rep(i,h) {
    //     rep(j,w) cout << d[i][j] << " ";
    //     cout << endl;
    // }
    int ans = d[goal.first][goal.second];
    if (ans == inf) cout << -1 << endl;
    else cout << ans << endl;
}

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
using ll = long long;
using vec = vector<ll>;
using vec2 = vector<vector<ll>>;
const ll inf = 1e18;
const ll mod = 1e9 + 7;

int main(){
  ll h, w;
  cin >> h >> w;
  vector<vector<char>> A(h,vector<char>(w));
  rep(i,h){
    rep(j,w){
      cin >> A[i][j];
    }
  }

  //yoko
  ll ans = 0;
  for(int i = 0;i < h;i++){
    for(int j = 0;j <= w-2;j++){
      if(A[i][j] == '.' && A[i][j+1] == '.'){
        ans++;
      }
    }
  }
  for(int i = 0;i <= h-2;i++){
    for(int j = 0;j < w;j++){
      if(A[i][j] == '.' && A[i+1][j] == '.'){
        ans++;
      }
    }
  }
  cout << ans << endl;

}


#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define endl "\n"
using namespace std;

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

    int n,m,t;
    cin >> n >> m >> t;
    pair<int,int> arr[m];
    for (int i=0;i<=m-1;i++)
    {
        cin >> arr[i].first >> arr[i].second;
    }

    int x=n;
    int time=0;
    bool ans=false;
    for (int i=0;i<=m-1;i++)
    {
        int a=arr[i].first-time;
        x=max(x-a,0);
        if (x==0)
        {
            ans=true;
        }
        int b=arr[i].second-arr[i].first;
        x=min(n,x+b);

        time=arr[i].second;
    }

    x=max(0,x-(t-time));
    if (x==0)
    {
        ans=true;
    }

    if (ans)
    {
        cout << "No" << endl;
    }
    else
    {
        cout << "Yes" << endl;
    }

    return 0;
}

#include<iostream>
using namespace std;

int main()
{
   int n, m, t;
   bool yee=true;
   cin>>n>>m>>t;
   int r=0;
   int last=0;
   int  mx=n;
      while(m--)
      {
		int a,b;
          cin>>a>>b;
           int now=a-last;
           n-=now;
           if(n<=0) {yee=false;}
           n=min(mx,(n+b-a));
           last=b;
      }
     // cout<<n<<" "<<t-last<<endl;
      n-=(t-last);
    // cout<<n<<endl;
      if(yee and n>0){cout<<"Yes"<<endl;}
      else cout<<"No"<<endl;
}


#include <bits/stdc++.h>
#define Rep(i,n,m) for(int i=(int)(n);i<(int)(m);i++)
#define rep(i,n) Rep(i,0,n)
#define all(v) v.begin(),v.end()
using namespace std;
using ll=long long;
using vi=vector<int>;
#define _GLIBCXX_DEBUG
const int mod=998244353;
int main(){
    int N;cin>>N;
    vector<int> f(N); rep(i,N) cin >> f[i];
    rep(i,N) f[i]--;
    vi a(N,-1);int count=0;
    rep(i,N){
        if(a[i]>=0) continue;
        a[i]=i;int x=i;
        while(a[f[x]]<0){
            x=f[x];
            a[x]=i;
        }
        if(a[f[x]]<i) continue;
        else count++;
    }
    ll x=2;
    ll ans=1;
    while(count>0){
        if(count&1) {
            ans*=x;
            ans%=mod;
        }
        count>>=1;
        x=x*x;x%=mod;

    }
    ans--;ans=(ans+mod)%mod;
    cout << ans << endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define drep(i,n) for (int i = (n)-1; i >= 0; --i)
#define dup(x,y) (((x)+(y)-1)/(y))
#define ALL(x) (x).begin(), (x).end()
typedef long long ll;
typedef pair<int, int> pii;
const double EPS = 1e-10;
const int INF = 1e9;
const ll LINF = 1e18;
const int MOD = 998244353;
const double PI = acos(-1);
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
template<typename T> bool chmax(T &a, T b) {if(a<b){a=b; return 1; } return 0; }
template<typename T> bool chmin(T &a, T b) {if(a>b){a=b; return 1; } return 0; }
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a;}
ll lcm(ll a, ll b) { return a/gcd(a,b)*b;}
ll mpow(ll x, ll p) {
	if (p==0) return 1;
	ll res=mpow(x,p/2); res=res*res%MOD;
	return p%2?res*x%MOD:res;
}
ll lpow(ll x, ll p) {
	if (p==0) return 1;
	ll res=lpow(x,p/2); res*=res;
	return p%2?res*x:res;
}

int main() {
	int tt;
	cin >> tt;
	while (tt--) {
		int n;
		cin >> n;
		vector<int> a(n);
		rep(i,n) cin >> a[i];
		map<int, int> mp;
		rep(i,n) mp[a[i]]++;
		if (n % 2 == 0) {
			bool b = true;
			for (auto p: mp) {
				if (p.second % 2 == 1) {
					b = false;
				}
			}
			if (b) cout << "Second" << endl;
			else cout << "First" << endl;
		} else {
			cout << "Second" << endl;
		}
	}
}


#include <bits/stdc++.h>

#define pb push_back
#define ff first
#define ss second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

const ll INF = (ll)1<<62;
const ll MOD = 1e9+7;
const int iINF = 1<<30;
const double PI = 3.14159265359;

void solve(){
  ll n;
  cin >> n;

  vector<ll> fib(105, 0);
  fib[0] = fib[1] = 1;
  for(int i=2;i<100;i++)
    fib[i] = fib[i-1]+fib[i-2];

  int s = 0;
  for(int i=1;i<100;i+=2){
    if(fib[i] > n){
      s = i;
      break;
    }
  }
  s--;

  vector<int> ans;
  vector<bool> taken(105, false);
  ll m = n;
  for(int i=s;i>=1;i--){
    if(m >= fib[i]){
      taken[i] = true;
      m -= fib[i];
    }
  }

  for(int i=s;i>=1;i-=2){
    if(taken[i-1])
      ans.pb(2);
    if(taken[i])
      ans.pb(1);

    ans.pb(4);
    ans.pb(3);
  }

  cout << ans.size() << "\n";
  for(int x : ans)
    cout << x << "\n";

}

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

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

  return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
#define int long long int
#define INF             1e14
#define dd              double
#define MOD             1000000007
#define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
#define nl              cout<<endl
#define fill(a,val)     memset(a,val,sizeof(a))
#define mp              make_pair
#define endl            "\n"
#define pb              push_back
#define ff              first
#define ss              second
#define SIZE            200005
#define all(v)          v.begin(),v.end()
#define s(ar,n)         sort(ar,ar+n)
#define rs(ar,n)        sort(ar, ar+n, greater<ll>())
#define oa(a,n)         for(ll i=0;i<n;i++)cout<<a[i]<<" ";nl
#define ain(a,n)         for(ll i=0;i<n;i++)cin>>a[i];
#define maxa(ar,N)      *max_element(ar,ar+N)
#define mina(ar,N)      *min_element(ar,ar+N)
#define fastio()        ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
// find_by_order() - 0 indexing
// order_of_key() - number of elements strictly smaller
int exp(int a,int b)
{
    int ans=1;
    for(int i =0;i<b;i++)ans*=a;
        return ans;
}
signed main()
{
    fastio();
    int tc=1;
   //cin>>tc;
    while(tc--){
     int n;cin>>n;
     int a[n],b[n];
     ain(a,n);ain(b,n);
     int x = maxa(a,n);
     int y =mina(b,n);
     if(x>y)cout<<0;
     else cout<<y-x+1;
} return 0;
    }


#include <bits/stdc++.h>
#define int long long
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define pre(i,a,b) for(int i=(b);i>=(a);i--)
#define ios ios::sync_with_stdio(false),cin.tie(0);
#define pb push_back
#define ps push
#define fi first
#define se second
#define ps push
#define Inf 0x3f3f3f3f3f3f3f3f
#define eps 1e-5
typedef long long ll;

const int N=3e5+5;
const int M=2e5+5;
const int mod=998244353;
using namespace std;

ll quick_power_mod(ll a,ll b,ll m)//pow(a,b)%m
{
    a%=m;
  ll result = 1;
  while(b>0)
  {
    if(b&1)
    result=(result*a)%m;
    a=(a*a)%m;
    b>>=1;
  }
  return result;
}
//计算组合数取模
ll comp(ll a,ll b,int p)//composite num C(a,b)%p
{
  if(a<b)return 0;
  if(a==b)return 1;
  if(b>a-b)b=a-b;
  ll ans=1,ca=1,cb=1;
  for(ll i=0;i<b;i++)
  {
    ca=(ca*(a-i))%p;
    cb=(cb*(b-i))%p;
  }
  ans=(ca*quick_power_mod(cb,p-2,p))%p;
  return ans;
}
ll lucas(ll n,ll m,ll p)
{
  ll ans=1;
  while(n&&m&&ans)
  {
    ans=(ans*comp(n%p,m%p,p))%p;//also can be recusive
    n/=p;
    m/=p;
  }
  return ans;
}

ll gcd(ll a,ll b){ return b==0?a:gcd(b,a%b); }
string   str;
signed main()
{
  ios;
  int n,q;
  cin>>n>>str>>q;
  int t,a,b;
  int cc=0;
  while(q--){
  	 cin>>t>>a>>b;
  	 if(t==1){
  	 	if(cc%2==0){

  	 	swap(str[a-1],str[b-1]);
		}
		else{
	    if(a<=n){
		a+=n;

		}
		else{
			a-=n;
		}
		if(b<=n){
		b+=n;

		}
		else{
			b-=n;
		}

		swap(str[a-1],str[b-1]);
		}
	 }
	 else{
	 	cc++;
	 //	swap(str[n-1],str[2*n-1]);
	 }
  }
  if(cc%2==0){
  	cout<<str<<endl;
  }
  else{
    for(int i=n;i<2*n;i++){
    	cout<<str[i];
	}
	for(int i=0;i<n;i++){
		cout<<str[i];
	}
	cout<<endl;
  }

  return 0 ;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define all(v) v.begin(),v.end()

const int mod = 1e9 + 7;

int main (){
    fast_io;
    int n;
    cin >> n;
    string s;
    cin >> s;
    string start = s.substr(0, n);
    string last = s.substr(n, n);
    int q;
    cin >> q;
    while (q--) {
        int type, a, b;
        cin >> type >> a >> b;
        a--, b--;
        if (type == 1) {
            if (a < n && b < n) {
                swap(start[a], start[b]);
            }
            else if (a < n && b >= n) {
                swap(start[a], last[b - n]);
            }
            else if (a >= n && b < n) {
                swap(start[a - n], last[b]);
            }
            else {
                swap(last[a - n], last[b - n]);
            }
        }
        else {
            swap(start, last);
        }
    }
    cout << start << last << endl;
}


/*
Another source code by:

  _   _ _ _   _        _____       _
 | \ | (_) | (_)      / ____|     | |
 |  \| |_| |_ _ _ __ | |  __ _ __ | |_
 | . ` | | __| | '_ \| | |_ | '_ \| __|
 | |\  | | |_| | | | | |__| | |_) | |_
 |_| \_|_|\__|_|_| |_|\_____| .__/ \__|
                            | |
                            |_|
*/
#include<bits/stdc++.h>
#include <vector>
using namespace std;
#define vi vector<int>
#define pb push_back
#define p push
#define sll stack<long long>
#define qll queue<long long>
#define vll vector<long long>
#define st string
#define vvll vector<vll>
#define vstr vector <string>
#define vp vector <pair<ll,ll>>
#define fori(n) for(ll i=0;i<n;i++)
#define forj(n) for(int j=0;j<n;j++)
#define fork(n) for(int k=0;k<n;k++)
#define fori1(n) for(int i=1;i<n;i++)
#define f(i,a,b) for(int i=a;i<=b;i++)
#define s(v) sort(v.begin(),v.end())
#define sr(v) sort(v.rbegin(),v.rend())
#define ll long long
#define MOD 1000000007
#define pi 3.14159265358979323
#include <math.h>
#define yn(n) if(n)cout<<"yes\n";else cout<<"no\n";
#define Yn(n) if(n)cout<<"Yes\n";else cout<<"No\n";
#define YN(n) if(n)cout<<"YES\n";else cout<<"NO\n";
#define mp   make_pair
#define ff first
#define ss second

ll gcd(ll a, ll b){if(b==0)return a;return gcd(b, a%b);}
ll lcm(ll a, ll b){return a*b/gcd(a, b);}
ll modify(ll n){ll res = n;res%=MOD;res+=MOD;res%=MOD;return res;}
ll md(ll n){if(n>0)return n;else return -n;}
ll mv(vll v){ll m=v[0];fori(v.size()){m=max(v[i],m);}return m;}
vll read(ll n){vll v(n);fori(n)cin>>v[i];return v;}
void out(vll v){fori(v.size()){cout<<v[i]<<" ";}cout<<"\n";}

void solve(){
    ll n,m,k,x;
    vector<pair<pair<int,int>,int>> v1,v2;
    cin>>n;
    fori(n){
        cin>>m>>k;
        v1.pb({{m,k},i});
        v2.pb({{k,m},i});
    }
    s(v1);
    s(v2);
    // fori(n){
    //     cout<<v1[i].first.first<<" "<<v1[i].first.second<<"\n";
    // }
    // cout<<"\n";
    // fori(n){
    //     cout<<v2[i].first.first<<" "<<v2[i].first.second<<"\n";
    // }
    // cout<<"\n";
    vll visited(n,0);
    vp temp;
    fori(n){
        if(i==0||i==1||i==n-2||i==n-1){
            if(visited[v1[i].second]==0){
                temp.pb(v1[i].first);
                visited[v1[i].second]=1;
            }
        }
    }
    fori(n){
        if(i==0||i==1||i==n-2||i==n-1){
            if(visited[v2[i].second]==0){
                temp.pb({v2[i].first.second,v2[i].first.first});
                visited[v2[i].second]=1;
            }
        }
    }
    vll ans;
    fori(temp.size()){
        for(int j=i+1;j<temp.size();j++){
            ans.pb(max(abs(temp[i].first-temp[j].first),abs(temp[i].second-temp[j].second)));
        }
    }
    sr(ans);

    cout<<ans[1];
}
int main(){

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

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

    }

    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";

}

#include <bits/stdc++.h>
namespace IO{
    char buf[1000000],*p1,*p2;
    inline char getc(){
        if(p1==p2) p2=(p1=buf)+fread(buf,1,10,stdin);
        return p1==p2?EOF:*(p1++);
    }
    template<typename tp>inline void r(tp &n){
        n=0;char c=getc();
        while(!isdigit(c)) c=getc();
        while( isdigit(c)) n=n*10+c-48,c=getc();
    }
    template<typename tp>inline void w(tp  n){
        if(n/10) w(n/10);
        putchar(n%10+48);
    }
};
using namespace IO;
const int N=2e5+5,K=3e2+5,Mod=998244353;
using namespace std;
int n,k;
int a[N],bin[K],s[N][K],c[K][K];
void Prework(){
    bin[0]=1;
    for(int i=1;i<=k;++i)
        bin[i]=bin[i-1]*2ll%Mod;
    c[0][0]=c[1][0]=1;
    for(int i=1;i<=k;++i,c[i][0]=1)
    for(int j=1;j<=i;++j)
        c[i][j]=(c[i-1][j-1]+c[i-1][j])%Mod;
    for(int i=1;i<=n;++i) s[i][0]=1;
    for(int i=1;i<=n;++i)
    for(int j=1;j<=k;++j)
        s[i][j]=1ll*s[i][j-1]*a[i]%Mod;
    for(int i=0;i<=k;++i)
    for(int j=2;j<=n;++j)
        s[j][i]=(s[j-1][i]+s[j][i])%Mod;
}
int solve(int d){
    int res=0;
    for(int i=0;i<=d;++i)
        res=(res+1ll*c[d][i]*s[n][i]%Mod*s[n][d-i]%Mod)%Mod;
    return res;
}
int Q(long long b,int t){
    long long ret=1;
    for(int i=1;i<=t;i<<=1,b=b*b%Mod)
        if(i&t) ret=ret*b%Mod;
    return ret;
}
int main(){

    r(n),r(k);
    for(int i=1;i<=n;++i)
        r(a[i]);
    Prework();
    int inv=Q(2,Mod-2);
    for(int i=1;i<=k;++i){
        int ans=solve(i);
        ans=(ans-1ll*bin[i]*s[n][i]%Mod+Mod)%Mod;
        w(1ll*ans*inv%Mod);putchar(10);
    }
    return 0;
}


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

#define int long long
const int MAXN = 2e1 + 5;

int fa[MAXN];
int find(int x) {
	return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y) {
    fa[find(y)] = find(x);
}

vector<int> vec;
int res, col[MAXN];
int n, m, g[MAXN][MAXN];
void dfs(int k) {
	if (k == vec.size()) {
		++res;
		return ;
	}
	for (int i = 1; i <= 3; ++i) {
		int u = vec[k];
		col[u] = i;
		auto check = [](int x) -> bool {
			for (int i = 1; i <= n; ++i)
				if (g[x][i] && col[i] == col[x])
					return false;
			return true;
		};
		if (check(vec[k])) dfs(k + 1);
		col[u] = 0;
	}
}
bool vis[MAXN];
signed main(int argc, char *argv[]) {
	//ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	for (int i = 0; i < MAXN; ++i) fa[i] = i;
	cin >> n >> m;
	while (m--) {
		int u, v;
		cin >> u >> v;
		merge(u, v);
		g[u][v] = g[v][u] = 1;
	}
	int ans = 1;
	for (int i = 1; i <= n; ++i) {
		if (vis[i]) continue;
		vec.clear(), res=  0;
		for (int j = 1; j <= n; ++j)
			if (find(j) == i) vec.push_back(j), vis[j] = true;;
		dfs(0);
		ans *= res;
	}
	cout << ans << '\n';
	system("pause");
	return 0;
}

#include <cstdio>
int n, x, sum, a, b;
int main() {
    scanf("%d%d", &n, &x);
    x *= 100;
    for(int i = 1; i <= n; i++){
        scanf("%d%d", &a, &b);
        sum += a*b;
        if(sum > x) return printf("%d", i), 0;
    }
    puts("-1");
}


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

int main(){
  int N;
  int total = 0;
  cin >> N;

  for(int i = 1;total < N;i++){
    total += i;
    if(total >= N){
      cout << i << endl;
      break;
    }
  }
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=1000000007;
#define INF 1LL<<30
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define all(x) (x).begin(),(x).end()

int main(){
    int n;
    cin>>n;
    vector<int> t(n);
    int sum=0;
    rep(i,n){
        cin>>t[i];
        sum+=t[i];
    }

    if(n==1){
        cout<<t[0]<<endl;
        return 0;
    }

    int ans;
    if(sum%2==0) ans=sum/2;
    else ans=sum/2+1;
    bool dp[n+10][sum+10];
    memset(dp, 0, sizeof(dp));
    dp[0][0] = true;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j <= sum+10; ++j) {
        dp[i+1][j] |= dp[i][j];
        if (j >= t[i]) dp[i+1][j] |= dp[i][j-t[i]];
      }
    }
    while(1){
        if(dp[n][ans]){
            cout<<ans<<endl;
            return 0;
        }
        ans++;
    }
}


#include <bits/stdc++.h>
#include <math.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vpl = vector<pair<ll, ll>>;
using pll = pair<ll, ll>;
#define rep(i, k, n) for(ll i = k; i < n; i++)
#define pb push_back
#define mp make_pair

//dijkstra + bitDP

ll n, m, k;
const ll INF = 10000000000000;
vll c(21);
vvll G(300000, vll(0));
vll dist(300000);
vvll cost(21, vll(21));
priority_queue<pll, vpl, greater<pll>> Q;

//dp[bit][v]:集合bitについて最後をvとして順序を最適化した時の最小コスト
vvll dp((1<<21)+1, vll(21));

ll rec(ll bit, ll v){
    //探索済みならリターン
    if(dp[bit][v] != -1) return dp[bit][v];

    //初期化(bitがvのみ)
    if(bit == (1<<v)) return dp[bit][v] = 0;

    //答えの変数
    ll res = INF;

    //bitからvを除いたもの
    ll prev_bit = bit & ~(1<<v);

    //vの一つ手前のuについて全探索
    rep(u, 0, k){
        //uがprev_bitに含まれない場合スルー
        if(!(prev_bit & (1<<u))) continue;

        //再帰的に探索
        if(res > rec(prev_bit, u) + cost[u][v]){
            res = rec(prev_bit, u) + cost[u][v];
        }
    }

    //メモ化してリターン
    return dp[bit][v] = res;
}

int main(){
    cin >> n >> m;
    rep(i, 0, m){
        ll a, b;
        cin >> a >> b;
        G[a].pb(b);
        G[b].pb(a);
    }

    cin >> k;
    rep(i, 0, k){
        cin >> c[i];
    }

    bool flag = true;

    rep(i, 0, k){
        //距離の初期化
        rep(j, 1, n+1){
            dist[j] = INF;
        }

        //優先度付きキューに(距離, 頂点番号)の組を入れる
        Q.push(mp(0, c[i]));
        dist[c[i]] = 0;
        while(!Q.empty()){
            ll pos = Q.top().second;
            Q.pop();
            rep(i, 0, G[pos].size()){
                ll to = G[pos][i];
                //posを経由してtoに行く距離がdist[to]より短ければ
                //dist[to]を更新してキューに入れる
                if(dist[to] > dist[pos] + 1){
                    dist[to] = dist[pos] + 1;
                    Q.push(mp(dist[to], to));
                }
            }
        }

        //コストの配列を作って入れる
        vll record(0);
        rep(j, 0, k){
            if(dist[c[j]] == INF){
                flag = false;
                break;
            }

            record.pb(dist[c[j]]);
        }
        cost[i] = record;
    }

    if(flag){
        //dpテーブルを-1で初期化
        rep(i, 0, (1<<k)){
            rep(j, 0, k){
                dp[i][j] = -1;
            }
        }

        //探索
        ll res = INF;
        rep(v, 0, k){
            if(res > rec((1<<k)-1, v)){
                res = rec((1<<k)-1, v);
            }
        }

        cout << res+1 << endl;
    }
    else cout << -1 << endl;

    return 0;
}

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

typedef long long ll;

ll x,y,r,ans;

ll inp(){
    string s;
    bool f=true,neg=false;
    cin>>s;
    if(s.front()=='-'){
        s.erase(s.begin());
        neg=true;
    }
    for(int i=0;i<s.size();i++)if(s[i]=='.'){
        while(s.size()<=i+4)s+='0';
        f=false;
    }
    if(f)s+="0000";
    ll res=0;
    for(char c:s)if(c!='.'){
        res=res*10+c-'0';
    }
    if(neg)res=-res;
    return res;
}

int main(){

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

    x=inp();y=inp();r=inp();
    ll px=x-r,lb=y+10000,rb=y-10000;
    while(lb%10000!=0)lb--;
    while(rb%10000!=0)rb++;
    while(px%10000!=0)px++;
    for(;px<=x+r;px+=10000){
        while(lb-10000>=y||(y-lb+10000)*(y-lb+10000)+(x-px)*(x-px)<=r*r)lb-=10000;
        while(rb+10000<=y||(rb-y+10000)*(rb-y+10000)+(x-px)*(x-px)<=r*r)rb+=10000;
        while((y-lb)*(y-lb)+(x-px)*(x-px)>r*r&&lb<y)lb+=10000;
        while((rb-y)*(rb-y)+(x-px)*(x-px)>r*r&&rb>y)rb-=10000;
        ans+=max(0ll,(rb-lb)/10000+1);
    }
    cout<<ans<<endl;

    return 0;
}


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

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define REP(i, n) for (int i = 0; i < (n); i++)
#define RREP(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define RFOR(i, a, b) for (int i = (a); i > (b); i--)
#define ALL(a) (a).begin(), (a).end()

int main() {
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    cout << a * d - b * c << endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main()
{

int n,c,i,j,x,y,z,m,l,k=0,op=0,c1=0,sum=0,x1,y1,po=1;
cin>>n>>x>>y>>z;
cout<<(n*z)-(x*y);

     return 0;
}


/*----------------------*/
/*----- Monazo1997 -----*/
/*----------------------*/

#include <bits/stdc++.h>
using namespace std;
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);

typedef long long ll;
#define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define forr(i, a, b) for(ll i = (a); i < (ll) (b); i++)
#define forn(i, n) forr(i, 0, n)
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define DBG(x) cerr << #x << " = " << (x) << endl
#define DBGV(v,n) forn(i,n) cout << v[i] << " "; cout << endl
#define esta(x,c) ((c).find(x) != (c).end())
#define RAYA cerr << "===============================" << endl
const ll MOD = (ll)(1e9+7); // 998244353
const ll INF = (ll)(1e7+10); // (1e18+10)
const int MAXN = (int)(2e5+5);

int main(){
   	FIN;

	ll a, b;
	cin >> a >> b;
	ll suma = 0;
	forn(i,a-1) {
		cout << i+1 << " ";
		suma += i+1;
	}
	suma += INF;
	cout << INF << " ";
	forn(i,b-1) {
		cout << -i-1 << " ";
		suma -= i+1;
	}
	cout << -suma << "\n";

	return 0;
}

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

int main(){
  int a,b,sa,wa;
  vector<int> god;
  cin>>a>>b;
  if(a==b){
    for(int i=1;i<=a;i++){
      god.push_back(i);
      god.push_back(-1*i);
    }
  }else if(a>b){
    sa=a-b;
    wa=0;
    for(int i=1;i<=sa+1;i++){
      god.push_back(i);
      wa+=i;
    }
    god.push_back(-1*wa);
    for(int i=0;i<b-1;i++){
      wa++;
      god.push_back(wa);
      god.push_back(-1*wa);
    }
  }else{
      sa=b-a;
    wa=0;
    for(int i=1;i<=sa+1;i++){
      god.push_back(-1*i);
      wa+=i;
    }
    god.push_back(wa);
    for(int i=0;i<a-1;i++){
      wa++;
      god.push_back(wa);
      god.push_back(-1*wa);
    }
  }
  for(int i=0;i<god.size();i++){
   cout<<god.at(i)<<" ";

  }
  cout<<endl;

}


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

#define fr(i,n) for(int i = 0; i<n; i++)
typedef long long ll;
#define rmin(a,b) a = min<ll>(a,b)

//solves https://atcoder.jp/contests/abc193/tasks/abc193_e

ll div(ll a, ll b, bool ceil){
	ll ans = abs(a/b);
	bool pos = (a<0)==(b<0);
	if(a%b and ceil==pos) ans++;
	if(!pos) ans*=-1;
	return ans;
}

ll gcd_ext(ll a, ll b, ll &xo, ll &yo){
	if(b==0){
		xo = 1, yo = 0;
		return a;
	}
	ll x1, y1;
	ll g = gcd_ext(b,a%b,x1,y1);
	xo = y1;
	yo = x1-(a/b)*y1;
	return g;
}

/*
Retorna qual o menor x positivo que satisfaz
a*x + b*y = c (obviamente o y correspondente eh negativo)
(ou -1 se nao existe)

Util em CRT para achar menor r positivo que
	r = ra (mod a)
	r = rb (mod b)
	->
	a*x-b*y = rb-ra
	r = a*x + ra
*/
ll qual_sol(ll a, ll b, ll c){
	ll xo, yo;
	ll g = gcd_ext(a,b,xo,yo);
	if(c%g!=0) return -1;
	c/=g, a/=g,b/=g;
	xo*=c,yo*=c;

	ll k = div(-xo,b,b>0);

	return xo+k*b;
}

/*
	Return minimun r such that:
		r = ra (mod a)
		r = rb (mod b)
	Or -1 if no such r
*/
ll solve_crt(ll ra, ll a, ll rb, ll b){
	ll minx = qual_sol(a,-b,rb-ra);
	if(minx==-1) return minx;
	return a*minx+ra;
}

int main(){
	ios::sync_with_stdio(0); cin.tie(0);
	ll t; cin >> t;
	fr(tt,t){
		ll X, Y, P, Q; cin >> X >> Y >> P >> Q;

		ll t1 = P+Q, t2 = 2*X+2*Y;
		ll ans = LLONG_MAX;
		fr(i,Q) fr(j,Y){
			ll cand = solve_crt(P+i,t1,X+j,t2);
			if(cand!=-1) rmin(ans,cand);
		}
		if(ans<LLONG_MAX){
			cout << ans << "\n";
		} else{
			cout << "infinity\n";
		}
	}
}

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<iomanip>
#include<cstdio>
#include<map>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;

int main(){
    int n;cin>>n;
    ll size=pow(2,n);
    ll res1=0,res2=0,maxv1=0,maxv2=0;
    for(int i=0;i<size/2;i++){
        ll tmp;cin>>tmp;
        if(tmp>maxv1){
            maxv1=tmp;
            res1=i+1;
        }
    }
    for(int i=size/2;i<size;i++){
        ll tmp;cin>>tmp;
        if(tmp>maxv2){
            maxv2=tmp;
            res2=i+1;
        }
    }
    if(maxv1>maxv2)cout<<res2<<endl;
    else cout<<res1<<endl;
    return 0;

}


#include <iostream>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>

using namespace std;
const int INF = 1 * (1 << 30);
const int mINF = -1 * (1 << 30);

int main()
{
  string s;
  cin >> s;
  if (s.find(".") != string::npos)
  {
    s.erase(s.find("."));
  }
  cout << s << endl;
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define _ 0
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    string x;
    cin>>x;
    for(int i=0;i<=x.size()-1;i++)
    {
    	if(x[i]=='.')
    		break;
    	cout<<x[i];
	}
	return ~~(0^_^0);
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;
using P = pair<int, int>;
#define rep(i,n) for(int i = 0; i < (n); i++)

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

#include<bits/stdc++.h>
using namespace std;
#pragma region atcoder
/*#include <atcoder/all>
using namespace atcoder;
//using mint = modint998244353;
//using mint = modint1000000007;*/
#pragma endregion
#pragma region macros
using ll = long long;
using pii = pair<int, int>;
template <class T> using V = vector<T>;
template <class T> using VV = V<V<T>>;
#define rep(i, n) for(int i = 0; i < n; i++)
#define REP(i, a, b) for(int i = a; i < b; i++)
#define rrep(i, n) for(int i = n - 1; i >= 0; i--)
#define RREP(i, a, b) for(int i = b - 1; i >= a; i--)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) ((int)(x).size())
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define fi first
#define se second
#pragma endregion
#pragma region debug for var, v, vv
#define debug(var)  do{std::cerr << #var << " : ";view(var);}while(0)
template<typename T> void view(T e){std::cerr << e << std::endl;}
template<typename T> void view(const std::vector<T>& v){for(const auto& e : v){ std::cerr << e << " "; } std::cerr << std::endl;}
template<typename T> void view(const std::vector<std::vector<T> >& vv){cerr << endl;int cnt = 0;for(const auto& v : vv){cerr << cnt << "th : "; view(v); cnt++;} cerr << endl;}
#pragma endregion
#pragma region int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {
  std::ostream::sentry s(dest);
  if (s) {
    __uint128_t tmp = value < 0 ? -value : value;
    char buffer[128];
    char *d = std::end(buffer);
    do {
      --d;
      *d = "0123456789"[tmp % 10];
      tmp /= 10;
    } while (tmp != 0);
    if (value < 0) {
      --d;
      *d = '-';
    }
    int len = std::end(buffer) - d;
    if (dest.rdbuf()->sputn(d, len) != len) {
      dest.setstate(std::ios_base::badbit);
    }
  }
  return dest;
}
#pragma endregion
const ll mod = 1000000007;
const int inf = 1001001001;
const ll INF = 1001001001001001001ll;

int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
template<class T>bool chmax(T &a, const T b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T b) { if (b<=a) { a=b; return 1; } return 0; }
ll rudiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } //  20 / 3 == 7
ll rddiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // -20 / 3 == -7
ll power(ll a, ll p){ll ret = 1; while(p){if(p & 1){ret = ret * a;} a = a * a; p >>= 1;} return ret;}
ll modpow(ll a, ll p){ll ret = 1; while(p){if(p & 1){ret = ret * a % mod;} a = a * a % mod; p >>= 1;} return ret;}
/*---------------------------------------------------------------------------------------------------------------------------------*/
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    //cout << fixed << setprecision(20);
    int n; cin >> n;
    vector<ll> a(n);
    for(int i = 0; i < n; i++) cin >> a[i];
    sort(a.begin(), a.end());
    ll ans = 0;
    for(int i = 0; i < n; i++){
        ans += (ll)(-1) * (n - 1 - i) * a[i] + (ll)i * a[i];
    }
    cout << ans << endl;
}
/*
   * review you code when you get WA (typo? index?)
   * int overflow, array bounds
   * special cases (n=1?)
*/


/*

  Author: Arnab Sinha

  ███████╗██╗  ██╗███████╗██████╗         ██╗      ██████╗  ██████╗██╗  ██╗███████╗██████╗  █████╗  █████╗
  ██╔════╝██║  ██║██╔════╝██╔══██╗        ██║     ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔══██╗
  ███████╗███████║█████╗  ██████╔╝        ██║     ██║   ██║██║     █████╔╝ █████╗  ██║  ██║╚██████║╚██████║
  ╚════ █║██╔══██║██╔══╝  ██╔══██╗        ██║     ██║   ██║██║     ██╔═██╗ ██╔══╝  ██║  ██║ ╚═══██║ ╚═══██║
  ███████║██║  ██║███████╗██║  ██║███████╗███████╗╚██████╔╝╚██████╗██║  ██╗███████╗██████╔╝ █████╔╝ █████╔╝
  ╚══════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚══════╝╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝╚═════╝  ╚════╝  ╚════╝
*/

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define li long long int
#define ld long double
#define all(v) v.begin(),v.end()
#define rev(a) reverse(all(a))
#define sort(a) sort(all(a))
#define pb push_back
#define INF 1e18+10
#define MINF -1e18-10
#define rep(i,a,b) for(li i=a;i<b;i++)
#define vli vector<li>
const li MAXN = 1e5+10;
const li mod = 998244353;
using namespace std;

li power(li a, li b, li mod) { a%=mod; li ret = 1; while(b){ if(b&1) ret*=a; a*=a;; if(ret>=mod) ret%=mod; if(a>=mod) a%=mod; b>>=1; } return ret; }

template <class T> void read(T& x){
	cin>>x;
}

template <class T, class... U> void read(T& x, U&... u){
	read(x);
	read(u...);
}

template <class A> void read(vector<A>& v){
	for(auto &it:v)
		read(it);
}

template <class A> void print(A x){
	cout<<x;
}

template <class A> void printl(A x){
	cout<<x<<endl;
}

template <class A> void print(vector<A>& v)
{
	for(auto &it:v){
		print(it);
		cout<<' ';
	}
	cout<<endl;
}

bool isprime(li n)
{
    if (n <= 1)
        return false;
    for (li i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}

li lcm(li a,li b){
	return (a*b)/__gcd(a,b);
}

void solve()
{
	li n;
	cin>>n;

	vli a(n),b(n);

	rep(i,0,n){
		li x,y;
		cin>>x>>y;
		a[i] = x;
		b[i] = y;
	}

	li ans = INF;

	rep(i,0,n){
		rep(j,0,n){
			if(i==j){
				ans = min(ans, a[i] + b[j]);
			}
			else
				ans = min(ans, max(a[i],b[j]));
		}
	}

	cout<<ans<<endl;
}

int main()
{
	IOS;

	// li t;
	// cin>>t;
	// while(t--)
		solve();

	return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>

int main(){
	int N;
	std::cin >> N;
	std::vector<int> A(N), B(N);
	for(int i=0; i<N; ++i){
		std::cin >> A.at(i) >> B.at(i);
	}
	int A_min=A.at(0), A_i=0, B_min=B.at(0), B_i=0;
	for(int i=0; i<N; ++i){
		if(A_min>A.at(i)){
			A_min = A.at(i); A_i = i;
		}
		if(B_min>B.at(i)){
			B_min = B.at(i); B_i = i;
		}
	}
	A.erase(A.begin()+A_i); B.erase(B.begin()+B_i);

	int A_min2=A.at(0), B_min2=B.at(0);
	for(int i=0; i<N-1; ++i){
		if(A_min2>A.at(i)) A_min2 = A.at(i);
		if(B_min2>B.at(i)) B_min2 = B.at(i);
	}

	int result;
	if(A_i == B_i) result = std::min(A_min+B_min, std::min(std::max(A_min,B_min2), std::max(A_min2,B_min)));
	else result = std::max(A_min,B_min);

	std::cout << result << std::endl;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<long long, long long>;
constexpr char ln =  '\n';
constexpr long long MOD = 1000000007;
constexpr long long INF = 1000000000 + 100;
constexpr long long LINF = 1000000000000000000 + 100;
#define all(v) v.begin(), v.end()
#define rep(i, n) for(int i=0;i<(n);i++)
#define rept(i, j, n) for(int i=(j); i<(n); i++)
#define rrep(i, n) for(int i=(n); i>=0; i--)
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int main(){
    int N; cin >> N; N = pow(2, N);
    vector<pll> A(N);
    rep(i, N){
        int a; cin >> a;
        A[i] = {i, a};
    }

    while(true){
        if(A.size()==2){
            if(A[0].second > A[1].second) cout << A[1].first + 1 << ln;
            else cout << A[0].first + 1 << ln;
            return 0;
        }

        vector<pll> v;
        for(int i=0; i<A.size(); i+=2){
            if(A[i].second > A[i+1].second)v.push_back(A[i]);
            else v.push_back(A[i+1]);
        }
        A = v;
    }
}

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

int main() {
    LL N, L, R;
    scanf("%lld",&N);
    L = 0, R = N + 1;
    while(L < R - 1) {
        LL mid = (L + R) / 2;
        //printf("%lld %lld %lld\n",L,R,mid);
        if (mid > 2e9) {
            R = mid;
        } else if ((mid + 1) * mid / 2 <= N + 1) {
            L = mid;
        } else {
            R = mid;
        }
    }
    printf("%lld\n",N + 1 - L);
}


#include<bits/stdc++.h>
using namespace std;
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1e9;
const ll MOD = 1000000007;
int main() {
    string S;
    cin >> S;
    REP(i, S.size() - 1) {
        i += 1;
        if(!('A' <= S[i] && S[i] <= 'Z')) {
            cout << "No" << endl;
            return 0;
        }

    }
    REP(i, S.size()) {
        if(!('a' <= S[i] && S[i] <= 'z')) {
            cout << "No" << endl;
            return 0;
        }
        i += 1;
    }
    cout << "Yes" << endl;
}

#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 pb push_back
#define eb emplace_back
#define sz size
#define ALL(v) v.begin(),v.end()
const long long INF = 1LL << 60;
using namespace std;
using ll = long long;
using P = pair<int, int>;
using LP = pair<ll, ll>;
using P3 = tuple<int, int, int>;
#define vi vector<int>
#define vvi vector<vi>
#define vll vector<ll>
#define vs vector<string>
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
ll gcd(ll a, ll b)
{
   if (a%b == 0)
   {
       return(b);
   }
   else
   {
       return(gcd(b, a%b));
   }
}

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

int main()
{
    ll l, n;
    cin >> n;
    l = 2;
    rep2(i, 2, n) l = lcm(l, i+1);
    cout << l+1 << endl;
    // rep2(i, 2, n+1) {
    //     l *= (ll)i;
    //     cout << l << endl;
    // }
    // cout << l+1 << endl;
    return 0;
}


#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#define rep(i, a, b) for (int i = int(a); i < int(b); i++)
using namespace std;
using ll = long long int;
using P = pair<ll, ll>;

// clang-format off
#ifdef _DEBUG_
#define dump(...) do{ cerr << __LINE__ << ":\t" << #__VA_ARGS__ << " = "; debug_print(__VA_ARGS__); } while(false)
template<typename T, typename... Ts> void debug_print(const T &t, const Ts &...ts) { cerr << t; ((cerr << ", " << ts), ...); cerr << endl; }
#else
#define dump(...) do{ } while(false)
#endif
template<typename T> vector<T> make_v(size_t a, T b) { return vector<T>(a, b); }
template<typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v(ts...))>(a, make_v(ts...)); }
template<typename T> bool chmin(T &a, const T& b) { if (a > b) {a = b; return true; } return false; }
template<typename T> bool chmax(T &a, const T& b) { if (a < b) {a = b; return true; } return false; }
template<typename T, typename... Ts> void print(const T& t, const Ts&... ts) { cout << t; ((cout << ' ' << ts), ...); cout << '\n'; }
template<typename... Ts> void input(Ts&... ts) { (cin >> ... >> ts); }
template<typename T> istream &operator,(istream &in, T &t) { return in >> t; }
// clang-format on

class UnionFind {
public:
    vector<int> par;
    int N;
    UnionFind(int n) {
        par.resize(n, -1);
        N = n;
    }
    int Find(int n) {
        return par[n] < 0 ? n : par[n] = Find(par[n]);
    }
    bool Union(int x, int y) {
        x = Find(x);
        y = Find(y);
        if (x == y) return false;
        if (-par[x] > -par[y]) swap(x, y);
        par[y] += par[x];
        par[x] = y;
        N--;
        return true;
    }
    bool Same(int x, int y) {
        return Find(x) == Find(y);
    }
    int size(int x) {
        return -par[Find(x)];
    }
    int size() {
        return N;
    }
};

int popcount(ll bits) {
    bits = (bits & 0x5555555555555555LL) + (bits >> 1 & 0x5555555555555555LL);
    bits = (bits & 0x3333333333333333LL) + (bits >> 2 & 0x3333333333333333LL);
    bits = (bits & 0x0f0f0f0f0f0f0f0fLL) + (bits >> 4 & 0x0f0f0f0f0f0f0f0fLL);
    bits = (bits & 0x00ff00ff00ff00ffLL) + (bits >> 8 & 0x00ff00ff00ff00ffLL);
    bits = (bits & 0x0000ffff0000ffffLL) + (bits >> 16 & 0x0000ffff0000ffffLL);
    return (bits & 0x00000000ffffffffLL) + (bits >> 32 & 0x00000000ffffffffLL);
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n, m;
    input(n, m);
    vector<P> edge(m);
    vector<ll> pow2(30, 1);
    rep(i, 1, 30) {
        pow2[i] = pow2[i - 1] * 2;
    }
    rep(i, 0, m) {
        int a, b;
        input(a, b);
        a--;
        b--;
        edge[i] = P(a, b);
    }
    int bits = 1 << n;
    ll ans = 0;
    rep(bit, 0, bits) {
        vector<bool> used(n, 0);
        rep(i, 0, n) {
            if ((bit >> i) & 1) {
                used[i] = true;
            }
        }
        UnionFind uf(2 * n), uf2(n);
        bool ok = true;
        for (auto [a, b] : edge) {
            if (used[a] && used[b]) {
                ok = false;
            } else if (used[a] || used[b]) {
                continue;
            } else {
                uf.Union(a, b + n);
                uf.Union(a + n, b);
                uf2.Union(a, b);
            }
        }
        for (auto [a, b] : edge) {
            if (!used[a] && !used[b]) {
                if (uf.Same(a + n, b + n)) {
                    ok = false;
                    break;
                }
            }
        }
        if (ok) {
            ans += pow2[uf2.size() - popcount(bit)];
        }
    }
    print(ans);
    return 0;
}

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(void){
    int n;
    cin >> n;
    vector< int > p(n+1);
    vector< vector< int > > p2c(n+1, vector< int >());
    for(int i = 2; i <= n; i++){
        cin >> p[i];
        p2c[p[i]].push_back(i);
    }

    vector< int > dp(n+1, -1), dpz(n+1, -1);

    auto f = [&](auto f, int v)->void{
        if(p2c[v].size() == 0){
            dp[v] = 1;
            dpz[v] = 1;
            return;
        }
        dp[v] = 1;
        vector< int > vp;
        int pn = 0;
        for(int w: p2c[v]){
            f(f, w);
            if(dp[w] < 0 && dpz[w] == 0){
                dp[v] += dp[w];
            }else if(dpz[w] == 0){
                pn += dp[w];
            }else{
                vp.push_back(dp[w]);
            }
        }
        sort(vp.begin(), vp.end());
        int vs = vp.size();
        for(int i = 0; i < vs; i++) dp[v] += (i%2 == 0 ? vp[i] : -vp[i]);
        dp[v] += (vs%2 == 0 ? pn : -pn);
        dpz[v] = (1-vs%2);
    };
    f(f, 1);
    cout << (n+dp[1])/2 << endl;
}


#include <iostream>

using namespace std;
typedef long long ll;

int main (void)
{
	ll b , c;
	cin >> b >> c;
	ll la , ra , lb , rb;

	ll ans = 0;

	if (b > 0)
	{
		lb = b - c / 2;
		rb = b + (c - 2) / 2;
		la = -b - (c - 1) / 2;
		ra = -(b - (c - 1) / 2);
		if (lb > ra)
			ans = rb - lb + ra - la + 2;
		else
			ans = rb - la + 1;
	}
	else
	{
		lb = b - c / 2;
		rb = b + (c - 2) / 2;
		la = -b - (c - 1) / 2;
		ra = -(b - (c - 1) / 2);
		if (la > rb)
			ans = ra - la + rb - lb + 2;
		else
			ans = ra - lb + 1;
	}
	cout << ans << endl;
	return 0;
}

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

int main(){
  ll b,c;cin>>b>>c;
  ll ans=0;
  bool f=true;
  if(b<0) f=false;
  b=abs(b);

  if(b==0){
    ans=c;
  }else if(c>2*b){
    if(f) ans=2*b+c-1;
    else ans=2*b+c;
  }else if(c>=3){
    ans=2*c-1;
  }else{
    ans=c+1;
  }

  cout<<ans<<endl;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll MOD = 1e9+7;

int solve_naive(const int n, const int s, const int k){
    int cnt = 0;
    ll now = s;
    while (now % n != 0 && cnt < n){
        now += k;
        cnt += 1;
    }
    if (cnt >= n){
        return -1;
    }
    return cnt;
}

ll _gcd(ll a, ll b){ return (a%b) ? _gcd(b, a%b) : b; }
pair<ll, ll> extgcd(ll a, ll b){
    // ax+by=gcd(a, b)なるx, yを求める
    if(a%b==0)return {0, 1}; // a*0+b*1=b
    const auto [x, y] = extgcd(b, a%b); // b*x + (a-a/b*b)*y = gcd(a, b)
    return {y, x-a/b*y}; // a*y + b*(x+a/b*y) = gcd(a, b)
}
ll powmod(ll x, ll n, ll p){
    // return (x ** n) mod p
    if (n==0)return 1;
    if(n==1)return x%p;
    const auto y = powmod(x, n/2, p);
    return (y*y%p)*powmod(x, n%2, p)%p;
}

int solve(int n, int s, int k){
    // s + a * k == 0 mod n なる最小の a を求める
    const auto g = _gcd(k, n);
    if(s%g!=0){
        // k, n が g の倍数なので s は g の倍数である必要がある
        return -1;
    }
    if(g>1){
        return solve(n/g, s/g, k/g);
    }
    // k*a == 1 mod n なる a を求める
    const auto [a, _] = extgcd(k, n);
    return ((n-s)*a%n+n)%n;
}

int main()
{
    int t;
    cin >> t;
    for(int ti=0; ti<t; ti++){
        int n,s,k;
        cin >> n >> s >> k;
        cout << solve(n, s, k) << endl;
    }
    return 0;
}


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

typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
const int INF = int (1e9) + int (1e5);
const ll INFL = ll(2e18) + ll(1e10);
const ui MOD = 1E9 + 7;
const double EPS = 1e-9;
#define FOR(i,n) for (int i=0;i<(n);++i)
#define ROF(i,x) for(int i = (x) ; i >= 0 ; --i)
#define MP make_pair
#define all(a) (a).begin(),(a).end()
#define ODD(x) ( ((x)&1)==0?0:1 )
#define SIGN(x) ( ((x) > 0) - ((x) < 0)  )
#define dbg(x) cerr << #x"= " << x << endl

std::mt19937_64  generator(std::chrono::system_clock::now().time_since_epoch().count());

inline ll powmod(ll a,ll b,ll mod) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a, ll b) { return a ? gcd(b%a, a): b; }
ll lcm(ll a, ll b) { return a / gcd(a,b) * b; }

void READ(bool _local){
    ios_base::sync_with_stdio(false); cin.tie(0);
#ifdef _DEBUG
    if (_local)
        freopen ("in.txt", "r", stdin);
#endif
}

int main() {
    READ(0);
    int n;cin>>n;
    vi a(n);
    FOR(i,n) cin>>a[i];
    sort(all(a));
    ll ret=a[0]+1;
    for(int i=1;i<n;++i){
        ret = ret * (a[i]-a[i-1]+1) % MOD;
    }
    cout << ret;

    return 0;
}

#include<iostream>
#include<iomanip>
#include<string>
#include<algorithm>
#include<vector>
#include<utility>
#include<tuple>
#include<map>
#include<queue>
#include<stack>
#include<deque>
#include<bitset>
#include<math.h>
#include<numeric>
using namespace std;
using ll = int64_t;
using Graph = vector<vector<int> >;
const ll M = 1000000007;

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

  sort(a.begin(),a.end());
  ll tmp=0;
  vector<ll> b(n);
  for(int i=0;i<n;i++){
    b[i]=a[i]-tmp;
    tmp=a[i];
  }

  for(int i=0;i<n;i++) b[i]++;

  ll ans=1;
  for(int i=0;i<n;i++){
    ans*=b[i];
    ans%=M;
  }

  cout << ans << endl;
}


#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
constexpr int MOD = 998244353;
constexpr int prob = 665496236;
long long dp[5001];

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

int main(){
    int H, W, K;
    scanf("%d%d%d", &H, &W, &K);

    vector<vector<pair<int, char>>> X(H);
    for(int i = 0; i < H; ++i) X[i].reserve(W);

    for(int i = 0; i < K; ++i){
        int x, y;
        char c;
        scanf("%d%d%c%c", &x, &y, &c, &c);
        --x, --y;
        X[x].emplace_back(y, c);
    }

    dp[0] = 1;
    for(int i = 0; i < H; ++i){
        sort(X[i].begin(), X[i].end());
        auto itr = X[i].begin();

        for (int j = 0; j < W; ++j){
            dp[j] %= MOD;
            if(itr != X[i].end() and itr->first == j){
                char c = itr->second;
                if(c != 'D') dp[j + 1] += dp[j];
                if((i != H - 1) & c == 'R') dp[j] = 0;
                ++itr;
            }
            else{
                dp[j + 1] += dp[j] * prob;
                if(i != H - 1) dp[j] *= prob;
            }
        }
    }

    long long ans = dp[W - 1];
    ans *= pow(3, H * W - K);
    printf("%d", ans % MOD);

    return 0;
}

#include <bits/stdc++.h>
#define fir first
#define sec second
#define PB push_back
#define MP make_pair
#define all(a) (a).begin(), (a).end()
#define sz(a) (a).size()

using namespace std;

#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep1(i, n) for (int i = 1; i < (int)(n); ++i)
#define foreach(itr, c) for (__typeof((c).begin()) itr = (c).begin(); itr != (c).end(); ++itr)

template <class T> void chkmax(T& x, T y) { x = (x > y ? x : y); }
template <class T> void chkmin(T& x, T y) { x = (x < y ? x : y); }

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

const int N = 5005;
const LL P = 998244353;

int n, m, K;
int a[N][N];
LL f[N][N];
bool vis[N][N];

LL mul1, mul2, mul3;

LL _pow(LL x, LL y){
    if (y < 0) return 0;
    LL ret = 1;
    for (; y; y >>= 1, x = x * x % P)
        if (y & 1) ret = ret * x % P;
    return ret;
}

LL dp(int r, int c){
    if (r == 1 && c == 1) return 1;
    if (vis[r][c]) return f[r][c];
    vis[r][c] = 1;
    LL& ret = f[r][c];

    if (r > 1 && a[r - 1][c] != 1){
        if (!a[r - 1][c]) ret += mul3 * dp(r - 1, c);
        else ret += dp(r - 1, c);
        ret %= P;
    }
    if (c > 1 && a[r][c - 1] != 2){
        if (!a[r][c - 1]) ret += mul3 * dp(r, c - 1);
        else ret += dp(r, c - 1);
        ret %= P;
    }

    return ret;
}

int main(){
    scanf("%d%d%d", &n, &m, &K);
    mul3 = _pow(3, P - 2);
    mul3 = mul3 * 2 % P;
    rep(i, K){
        int x, y; char c;
        scanf("%d%d %c", &x, &y, &c);
        if (c == 'R') a[x][y] = 1;
        if (c == 'D') a[x][y] = 2;
        if (c == 'X') a[x][y] = 3;
    }

    LL ret = dp(n, m);
    ret = ret * _pow(3, n * m - K) % P;
    printf("%lld\n", ret);
    return 0;
}


// Problem: E - Come Back Quickly
// Contest: AtCoder - AtCoder Beginner Contest 191
// URL: https://atcoder.jp/contests/abc191/tasks/abc191_e
// Memory Limit: 1024 MB
// Time Limit: 3000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define ll long long
#define mod 1000000007

// templates
#define all(v) v.begin(), v.end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define po(x, y) fixed << setprecision(y) << x
#define ss(s) scanf(" %[^\n]%*c", s)
#define sc(n) scanf("%d", &n)
#define sl(n) scanf("%lld", &n)
#define ps(s) printf("%s\n", s)
#define pr(n) printf("%d\n", n)
#define pl(n) printf("%lld\n", n)
#define prs(n) printf("%d ", n)
#define pls(n) printf("%lld ", n)
using namespace std;

const ll inf = (ll)1e15 + 10;
const int N = (int)2e3 + 10;
ll dist[N][N];
ll bk[N][N];
vector<pair<int, ll>> adj[N];
vector<ll> ans;
void bfs(int node) {
  queue<pair<int, ll>> q;
  dist[node][node] = 0;
  q.push({node, 0});
  while (sz(q)) {
    auto t = q.front();
    q.pop();
    for (auto child : adj[t.F]) {
      if (child.S + t.S < dist[node][child.F]) {
        dist[node][child.F] = child.S + t.S;
        q.push({child.F, child.S + t.S});
      }
    }
  }
}
void solve() {
  int n, m;
  sc(n), sc(m);
  ll c;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      dist[i][j] = inf;
      bk[i][j] = inf;
    }
  }
  vector<array<ll, 3>> ar;
  for (int i = 1; i <= m; i++) {
    int u, v;

    sc(u), sc(v), sl(c);
    bk[u][v] = c;
    ar.push_back({u, v, c});
  }
  sort(all(ar));
  for (int i = 0; i < m; i++) {
    int u = ar[i][0], v = ar[i][1];
    ll c = ar[i][2];
    if (i && u == ar[i - 1][0] && v == ar[i - 1][1]) {
      continue;
    }
    adj[u].push_back({v, c});
  }
  for (int i = 1; i <= n; i++) {
    bfs(i);
  }
  // printf("swapno\n");
  for (int i = 1; i <= n; i++) {
    ll mn = inf;
    for (auto p : adj[i]) {
      mn = min(mn, p.S + dist[p.F][i]);
    }
    if (mn == inf) {
      pr(-1);
    } else {
      pl(mn);
    }
  }
}

int main() {
  // #ifndef ONLINE_JUDGE
  // 	freopen("input.txt", "r", stdin);
  // 	freopen("output.txt", "w", stdout);
  // #endif
  int t = 1;
  // sc(t);
  while (t--) {
    solve();
  }
  //	cerr << (float)clock() / CLOCKS_PER_SEC * 1000 << " ms" << endl;
  return 0;
}

#pragma GCC optimize("Ofast", "unroll-loops")

#include <bits/stdc++.h>

using namespace std;

template<typename T>
vector<T> dijkstra(int s, vector<vector<pair<int, T>>> &G){
    const int n = G.size();
    vector<T> d(n, numeric_limits<T>::max());
    vector<int> b(n, -1);
    priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> q;
    d[s] = 0;
    q.emplace(d[s], s);
    while (!q.empty()){
        pair<T, int> p = q.top();
        q.pop();
        int v = p.second;
        if (d[v] < p.first) continue;
        for (auto& e : G[v]){
            int u = e.first;
            T c = e.second;
            if (d[u] > d[v] + c){
                d[u] = d[v] + c;
                b[u] = v;
                q.emplace(d[u], u);
            }
        }
    }
    return d;
}

using edge = pair<int, int>;

int N, M;
vector<vector<edge>> G, transG;

void input(void){
	cin >> N >> M;
	G.resize(N);
	transG.resize(N);
	for (int i = 0; i < M; ++i){
		int A, B, C;
		cin >> A >> B >> C;
		--A, --B;
		G[A].emplace_back(B, C);
		transG[B].emplace_back(A, C);
	}
}

int solve(int v){
	const int INF = numeric_limits<int>::max();
	auto mindist = dijkstra(v, G);
	int ans = INF;
	for (edge e : transG[v]){
		if (mindist[e.first] == INF)
			continue;
		ans = min(ans, e.second + mindist[e.first]);
	}
	if (ans == INF) return -1;
	return ans;
}

int main(void){
	input();
	for (int i = 0; i < N; ++i)
		cout << solve(i) << endl;
	return 0;
}


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

int a,b,c;
int main(){
  cin>>a>>b>>c;
  set<int> se;

  se.insert(a);
  se.insert(b);
  se.insert(c);

  if(se.size()==3)cout<<0<<endl;
  else{
    if(a==b)cout<<c<<endl;
    else if(b==c)cout<<a<<endl;
    else cout<<b<<endl;
  }
}

#include <bits/stdc++.h>

const long long INF = 1e9;
const long long MOD = 1e9 + 7;
//const long long MOD = 998244353;
const long long LINF = 1e18;
using namespace std;

#define YES(n) cout << ((n) ? "YES" : "NO"  ) << endl
#define Yes(n) cout << ((n) ? "Yes" : "No"  ) << endl
#define POSSIBLE(n) cout << ((n) ? "POSSIBLE" : "IMPOSSIBLE"  ) << endl
#define Possible(n) cout << ((n) ? "Possible" : "Impossible"  ) << endl
#define dump(x)  cout << #x << " = " << (x) << endl
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<(n);++i)
#define REPR(i,n) for(int i=n;i>=0;i--)
#define COUT(x) cout<<(x)<<endl
#define SCOUT(x) cout<<(x)<<" "
#define VECCOUT(x) for(auto&youso_: (x) )cout<<right<<setw(10)<<youso_<<" ";cout<<endl
#define ENDL cout<<endl
#define CIN(...) int __VA_ARGS__;CINT(__VA_ARGS__)
#define LCIN(...) long long __VA_ARGS__;CINT(__VA_ARGS__)
#define SCIN(...) string __VA_ARGS__;CINT(__VA_ARGS__)
#define VECCIN(x) for(auto&youso_: (x) )cin>>youso_
#define mp make_pair
#define PQ priority_queue<long long>
#define PQG priority_queue<long long,V,greater<long long>>

typedef long long ll;
typedef vector<long long> vl;
typedef vector<long long> vi;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<vl> vvl;
typedef vector<vi> vvi;
typedef vector<vb> vvb;
typedef vector<vc> vvc;
typedef pair<long long, long long> pll;

#define COUT(x) cout<<(x)<<endl
void CINT(){}
template <class Head,class... Tail>
void CINT(Head&& head,Tail&&... tail){
    cin>>head;
    CINT(move(tail)...);
}
template<class T>
void mod(T &x) {
    x %= MOD;
    x += MOD;
    x %= MOD;
}

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

struct COMB{
    vl fact, fact_inv, inv;
    void init_nCk(long long SIZE) {
        fact.resize(SIZE + 5);
        fact_inv.resize(SIZE + 5);
        inv.resize(SIZE + 5);
        fact.at(0) = fact.at(1) = fact_inv.at(0) = fact_inv.at(1) = inv.at(1) = 1;
        for(long long i = 2; i < SIZE + 5; i++) {
            fact.at(i) = fact.at(i - 1)*i%MOD;
            inv.at(i) = MOD - inv.at(MOD%i)*(MOD/i)%MOD;
            fact_inv.at(i) = fact_inv.at(i - 1)*inv.at(i)%MOD;
        }
    }
    long long nCk (long long n, long long k) {
        assert(!(n < k));
        assert(!(n < 0 || k < 0));
        return fact.at(n)*(fact_inv.at(k)*fact_inv.at(n - k)%MOD)%MOD;
    }
};
ll extGCD(ll a, ll b, ll &x, ll &y) {
    if(b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extGCD(b, a%b, y, x);
    y -= a/b*x;
    return d;
}

void Main() {
    LCIN(X);
    cout << 100 - X%100 << endl;
}

int main() {
    cout << fixed << setprecision(15);
    Main();
    return 0;
}


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

int main(){
    int N;
    cin >> N;
    long long S=0,ans=0;
    vector<long long> A(N);
    for(int i=0;i<N;i++){
        cin >> A[i];
        S+=A[i];
    }
    sort(A.begin(),A.end());
    for(int i=0;i<N;i++){
        ans+=S-(N-i)*A[i];
        S-=A[i];
    }
    cout << ans << endl;
}

#include <bits/stdc++.h>
#include <numeric>
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define RREP(i, n) for (int i = (int)(n) - 1 ; i >= 0; i--)
#define FOR(i, a, b) for (int i = (a); i < (int)(b); i++)
#define ALL(v) (v).begin(), (v).end()
#define MIN(v) *min_element((v).begin(), (v).end())
#define MAX(v) *max_element((v).begin(), (v).end())
#define PF(p) (p).first
#define PS(p) (p).second
#define MF(p) (p)->first
#define MS(p) (p)->second
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair
#define VL vector<long long>
#define VVL vector<vector<long long>>
#define VB vector<bool>
#define VVB vector<vector<bool>>
#define VC vector<char>
#define VVC vector<vector<char>>
using namespace std;
using ll = long long;
const ll MOD = 1000000007LL;
//const ll MOD = 998244353LL;
int pmod(int x){int y=x%(int)MOD;return (y>=0)?y:y+(int)MOD;}
ll pmod(ll x){ll y=x%MOD;return (y>=0LL)?y:y+MOD;}
bool in(ll x, ll a, ll b){return (a<=x)&&(x<b);}
template<class T>bool chmin(T& a, T b){if(a>b){a=b;return true;}else return false;}
template<class T>bool chmax(T& a, T b){if(a<b){a=b;return true;}else return false;}

int main(){
    ll N;
    cin>>N;
    VL A(N);
    REP(i,N)cin>>A[i];
    sort(ALL(A));
    ll sum = 0;
    for(ll i=0LL;i<N;++i){
        sum += (2LL*i-N+1LL) * A[i];
    }
    cout << sum;
    return 0;
}


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

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

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

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

	int N = getint();
	rep(i, N) {
		A[i] = ll(i) << 32 | getint();
		B[i] = ll(i) << 32 | getint();
	}
	pakuri_sort(N, A);
	pakuri_sort(N, B);

	const ll ma = (1ll << 32) - 1;
	rep(i, N) {
		auto tmp = (A[i] & ma) < (B[N - 1 - i] & ma);
		cn[A[i] >> 31] = tmp;
		cn[B[N - 1 - i] >> 31 | 1] = tmp;
	}

	int c = -1, pn = 0;
	rep(i, N << 1) {
		if (c != -1 && pn == cn[i]) {
			cn[c] = '(';
			cn[i] = ')';
			c = tmp[c];
			pn ^= 1;
		}
		else {
			pn = cn[i];
			tmp[i] = c;
			c = i;
		}
	}
	fwrite(cn, 1, N << 1, stdout);

	Would you please return 0;
}

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

//======================
//
// Template OleschY
//
// Die M�glichkeiten der deutschen Grammatik k�nnen
// einen, wenn man sich darauf, was man ruhig, wenn
// man m�chte, sollte, einl�sst, �berraschen.
// - @Gedankenbalsam
//
//======================

//======================
// Solution Single testcase
//======================

int solve()
{
    int n;
    cin >> n;
    vector<int> bra(2 * n);
    vector<bool> col(2 * n, false);
    for(int i = 0; i < 2 * n; ++i)
    {
        cin >> bra[i];
    }
    vector<int> id(2 * n);
    iota(id.begin(), id.end(), 0);
    sort(id.begin(), id.end(), [&](int a, int b)
    {
        return bra[a] < bra[b];
    });
    for(int i = 0; i < n; ++i)
    {
        col[id[i]] = true;
    }

    stack<int> stk;
    string sol;
    for(int i = 0; i < 2 * n; ++i)
    {
        if(stk.empty())
        {
            sol += '(';
            stk.push(i);
            continue;
        }
        int pos = stk.top();
        if(col[pos] == col[i])
        {
            sol += '(';
            stk.push(i);
        }
        else
        {
            sol += ')';
            stk.pop();
        }
    }

    cout << sol << "\n";
    return 0;
}

//======================
// Technical stuff
//======================

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    //freopen("a.out","w",stdout); // console output is better (in most cases)
#else
    // add i/o method of specific testing system
#endif
    int ntest = 1;
    //cin >> ntest;
    for(int test = 0; test < ntest; ++test)
    {
        solve();
    }
    return 0;
}


#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<list>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#include<tuple>
#include<cstring>
#include<bitset>

#define REP(i,n) for(ll i=0;i<(ll)n;i++)
#define ALL(x) (x).begin(),(x).end()
#define SZ(x) ((ll)(x).size())
#define pb push_back
#define eb emplace_back

#define INF 1000000000
#define INFLL 1000000000000000000LL

using namespace std;

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

using ll = long long;
using PP = pair<ll, ll>;

#define MAX_N 200000+100

class UnionFind {

	vector<int> par;//親

	vector<int> ran;//rank

public:

	UnionFind(int n) {
		par.resize(n);
		ran.resize(n);
		for (int i = 0; i < n; i++) {
			par[i] = i;
			ran[i] = 0;
		}
	}

	void init(int n) {
		par.resize(n);
		ran.resize(n);
		for (int i = 0; i < n; i++) {
			par[i] = i;
			ran[i] = 0;
		}
	}

	//根を求める
	int find(int x) {
		if (par[x] == x) {
			return x;
		}
		else
			return par[x] = find(par[x]);//辺の縮約を行っている
	}

	//併合
	void unite(int x, int y) {
		x = find(x);
		y = find(y);
		if (x == y)return;

		if (ran[x] < ran[y]) {
			par[x] = y;
		}
		else {
			par[y] = x;
			if (ran[x] == ran[y])ran[x]++;
		}
	}

	//同じ木に属するか
	bool same(int x, int y) {
		return find(x) == find(y);
	}
};

int N, Q, C[MAX_N], bel[MAX_N];
map<ll, ll> mp[MAX_N];
vector<ll> aff[MAX_N];

int main() {

	cin >> N >> Q;
	REP(i, N) {
		cin >> C[i];
		C[i]--;
	}

	REP(i, N) {
		bel[i] = i;
		mp[bel[i]][C[i]] = 1;
		aff[i].push_back(i);
	}

	UnionFind uf(N);

	while (Q--) {
		int a, x, y;
		cin >> a >> x >> y;
		x--, y--;
		if (a == 1) {
			if (!uf.same(x, y)) {
				uf.unite(x, y);

				if (SZ(aff[bel[x]]) > SZ(aff[bel[y]]))
					swap(x, y);

				ll belx = bel[x];

				for (auto&& v : aff[belx]) {
					aff[bel[y]].push_back(v);
					bel[v] = bel[y];
				}

				aff[belx].clear();

				for (auto&& m : mp[belx]) {
					mp[bel[y]][m.first] += m.second;
				}

				mp[belx].clear();
			}
		}
		if (a == 2) {
			cout << mp[bel[x]][y] << endl;
		}
	}

	return 0;
}

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <deque>
#include <ios>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <utility>

using namespace std;

using i64 = int64_t;
using u64 = uint64_t;
using i32 = int32_t;
using pi64 = pair<i64, i64>;

constexpr i64 MAXN = 3*100*1000LL+5LL;
constexpr i64 MOD = 1000000007LL;
constexpr i64 INF64 = MOD * MOD;
#define vec vector
#define let const
#define DRi64(x) i64 x; cin >> x;
#define DRS(x) string x; cin >> x;
#define DRVi64(v, n) vec<i64> v(n); { for (i64 i = 0; i < n; ++i) { cin >> v[i]; }}

#ifdef DEBUG
#define P(x) cerr << x << "\n"
#else
#define P(x)
#endif

i64
find_(const i64 a, vec<i64>& parents)
{
    if (parents[a] != a)
    {
        parents[a] = find_(parents[a], parents);
    }
    return parents[a];
}

void
union_(const i64 a, const i64 b, vec<i64>& parents, vec<i64>& sizes,
        vec<map<i64, i64>>& class_hists)
{
    let i64 r_a = find_(a, parents);
    let i64 r_b = find_(b, parents);
    if (r_a == r_b)
    {
        return;
    }
    if (sizes[r_a] < sizes[r_b])
    {
        union_(r_b, r_a, parents, sizes, class_hists);
        return;
    }
    sizes[r_a] += sizes[r_b];
    parents[r_b] = r_a;
    // merge map of smaller vertex into that of larger vertex
    for (let auto& [cls, cnt] : class_hists[r_b])
    {
        class_hists[r_a][cls] += cnt;
    }
}

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

    DRi64(N); DRi64(Q);
    DRVi64(C, N);

    // Ci \in [1, N]
    vec<i64> class_hist(N + 1, 0);
    for (let i64 c : C)
    {
        ++class_hist[c];
    }

    vec<i64> parents(N + 1);
    iota(parents.begin(), parents.end(), 0LL);
    vec<i64> sizes(N + 1, 1);
    vec<map<i64, i64>> class_hists(N + 1);
    for (i64 i = 1; i <= N; ++i)
    {
        class_hists[i][C[i - 1]] = 1;
    }

    for (; Q-->0;)
    {
        DRi64(typ);
        if (typ == 1)
        {
            DRi64(A); DRi64(B);
            union_(A, B, parents, sizes, class_hists);
        }
        else if (typ == 2)
        {
            DRi64(X); DRi64(Y);
            if (let i64 r_X = find_(X, parents); class_hists[r_X].count(Y))
            {
                cout << class_hists[r_X][Y] << "\n";
            }
            else
            {
                cout << "0\n";
            }
        }
        else
        {
            abort();
        }
    }

    return 0;
}


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

int charToInt(char c){
    char zero_num = '0';
    return (int)c - (int)zero_num;
}
int solve(vector<vec_int> &DP, vector<vec_int> &mat, int state, int pos, int K){
    if(DP.at(state).at(pos)>=0){
        return DP.at(state).at(pos);
    }
    int temp=1;
    vec_int city_vec;
    rep(i,K){
        if((state/temp)%2==1 && i!=pos){
            city_vec.push_back(i);
        }
        temp*=2;
    }
    if(city_vec.size()==0){
        DP.at(state).at(pos) = 1;
        return 1;
    }

    int next_state = state - (1<<pos);

    int result = INT_MAX;
    for(auto next_city: city_vec){
        int temp = solve(DP, mat, next_state, next_city, K) + mat.at(next_city).at(pos);
        result = min(temp, result);
    }
    DP.at(state).at(pos) = result;
    return result;
}
signed main(){
    int N, M; cin>>N>>M;
    vec_int A(M), B(M); rep(i,M)cin>>A.at(i)>>B.at(i);
    vector<vec_int> G(N+1);
    rep(i,M){
        G.at(A.at(i)).push_back(B.at(i));
        G.at(B.at(i)).push_back(A.at(i));
    }

    int K; cin>>K;
    vec_int C(K); rep(i,K)cin>>C.at(i);
    vector<vec_int> mat(K, vec_int(K,-1));

    rep(k,K){
        int start = C.at(k);
        priority_queue<P, vector<P>, greater<P>> pq;
        pq.emplace(0, start);
        vec_int visited(N+1, -1);
        while(!pq.empty()){
            int cost, pos; tie(cost, pos) = pq.top(); pq.pop();
            if(visited.at(pos)>=0)continue;
            visited.at(pos) = cost;
            for(auto next_pos: G.at(pos)){
                if(visited.at(next_pos)>=0)continue;
                pq.emplace(cost+1, next_pos);
            }
        }
        rep(i,K){
            mat.at(k).at(i) = visited.at(C.at(i)); //都市kからiまでの最短コスト, -1の時には到達不能
            if(visited.at(C.at(i))==-1){
                cout<<-1<<endl;
                return 0;
            }
        }
    }

    // TSPをbitDPで解く
    // DP.at(i).at(j): 今までの回った年: i, 最後の都市i
    vector<vec_int> DP(1<<K, vec_int(K, -1));
    int ans = INT_MAX;
    rep(i,K){
        ans = min(ans, solve(DP, mat, (1<<K)-1, i, K));
    }
    cout<<ans<<endl;

    return 0;
}

#include <bits/stdc++.h>

#define rep(i,n) for(int i=0; i<(n); ++i)
#define fixed_setprecision(n) fixed << setprecision((n))
#define execution_time(ti) printf("Execution Time: %.4lf sec\n", 1.0 * (clock() - ti) / CLOCKS_PER_SEC);
#define pai 3.1415926535897932384
#define NUM_MAX 2e18
#define NUM_MIN -1e9

using namespace std;
using ll = long long;
using P = pair<int,int>;
template<class T> inline bool chmax(T& a, T b){ if(a<b){ a=b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b){ if(a>b){ a=b; return 1; } return 0; }

#define DISPLAY_CNT 10
ll h[DISPLAY_CNT] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
map<char, ll> m;

ll SendMoreMoney(string S){
    ll n=0;
    ll l=S.length()-1;
    for(auto s:S){
        n += m[s] * pow(10, l);
        l--;
    }
    return n;
}

int main() {
    string s1, s2, s3;
    cin >> s1 >> s2 >> s3;

    for(auto s:s1) m[s]=0;
    for(auto s:s2) m[s]=0;
    for(auto s:s3) m[s]=0;

    if(m.size()>DISPLAY_CNT){
        cout << "UNSOLVABLE" << endl;
        return 0;
    }

    do{
        ll cnt=0;
        for(auto &itr:m){
            itr.second = h[cnt];
            cnt++;
        }
        if(m[s1[0]] == 0 || m[s2[0]] == 0 || m[s3[0]] == 0) continue;

        ll n1=SendMoreMoney(s1);
        ll n2=SendMoreMoney(s2);
        ll n3=SendMoreMoney(s3);

        if(n1 + n2 == n3){
            cout << n1 << endl << n2 << endl << n3 << endl;
            return 0;
        }

    }while(next_permutation(h, h+DISPLAY_CNT));

    cout << "UNSOLVABLE" << endl;

    return 0;
}


#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <functional>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
#define fi first
#define se second
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i < (n); ++i)
#define srep(i, s, n) for (int i = s; i < (n); ++i)
#define rng(a) a.begin(), a.end()
#define rrng(a) a.rbegin(), a.rend()
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
using ll = long long;
using ull = unsigned long long;
using P = pair<int, int>;
using T3 = tuple<int, int, int>;
template<typename T>void print(vector<T> a) { for (T t : a) { cout << t << " "; } cout << endl; }
const ll LINF = 1LL << 60;
const int INF = 1001001001;
const int mod = 1e9 + 7;

vector<vector<int> > g;
vector<bool> visited;

ll f(int i) {
    ll res = 0;

    // for (int next : g[i])
    // res += g[i].size();
    for (int next : g[i]) {
        if (!visited[next]) {
            visited[next] = true;
            res++;
            res += f(next);
        }
    }
    return res;
}

int main() {
    int n, m;
    cin >> n >> m;
    g = vector<vector<int> >(n);
    rep(i, n) { g[i].pb(i); }
    rep(i, m) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        g[a].pb(b);
    }

    // rep(i, n) { print(g[i]); }

    ll ans = 0;
    rep(i, n) {
        visited = vector<bool>(n, false);
        // cout << ans << endl;
        ans += f(i);
    }
    cout << endl;
    cout << ans << endl;
    return 0;
}

#include <bits/stdc++.h>
#define ll long long
#define rgi register int
using namespace std;
const int M=2e3+7,modd=998244353;
int n,m;
bitset<M>a[M];
inline int read(){
	int w=0,r=1;char c=getchar();
	while(!(isdigit(c)||c=='-'))c=getchar();
	if(c=='-'){r=-1;c=getchar();}
	while(isdigit(c)){w=(w<<3)+(w<<1)+c-'0';c=getchar();}
	return w*r;
}
int main(){
	int t=1;
	while(t--){
		n=read(),m=read();
		for(int i=1;i<=m;i++){
			int fr=read(),tr=read();
			a[fr][tr]=1;
		}
		for(int i=1;i<=n;i++)a[i][i]=1;
		for(int k=1;k<=n;k++){
			for(int i=1;i<=n;i++){
				if(a[i][k])a[i]|=a[k];
			}
		}
		int ans=0;
		for(int i=1;i<=n;i++)ans+=a[i].count();
		printf("%d\n",ans);
	}
	return 0;
}
/*
3 3
1 2
2 3
3 2
*/


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

#define pb push_back
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define REP(i,n) for(int _n=n, i=0;i<_n;++i)
#define FOR(i,a,b) for(int64_t i=(a),_b=(b);i<=_b;++i)
#define FORD(i,a,b) for(int64_t i=(a),_b=(b);i>=_b;--i)
using ull = uint64_t;
using ll = int64_t;
using PII = pair<int, int>;
using VI = vector<int>;

string to_string(string s) { return '"' + s + '"'; }
string to_string(const char* s) { return to_string((string) s); }
string to_string(bool b) { return (b ? "true" : "false"); }
template <typename A, typename B> string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A> string to_string(A v) {
bool first = true; string res = "{";
for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); }
res += "}"; return res; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)

const ll md = 1000000007;

bool canReach(ll a, ll b, ll c, ll d) {
    if (a + b == c + d || a - b == c - d || abs(a - c) + abs(b - d) <= 3) {
    	return true;
    }
    return false;
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    ll a, b, c, d;
    cin >> a >> b >> c >> d;
    if (a == c && b == d) {
    	cout << 0 << endl;
    	return 0;
    }
    if (canReach(a, b, c, d)) {
    	cout << "1\n";
    	return 0;
    }
    if ((c + d - a + b) % 2 == 0 && (a - b + c + d) % 2 == 0) {
    	cout << 2 << endl;
    	return 0;
    }
    if ((a + b +c - d) % 2 == 0 && (a + b - c + d) % 2 == 0) {
    	cout << 2 << endl;
    	return 0;
    }
    for (ll x = c - 6; x <= c + 6; x++) {
    	for (ll y = d - 6; y <= d + 6; y++) {
    		if (abs(x - c) + abs(y - d) > 3) continue;
    		if (canReach(a, b, x, y)) {
    			cout << "2\n";
    			return 0;
    		}
    	}
    }
    cout << 3 << endl;

}

#include <algorithm>
#include <cstdio>
#include <cmath>
using std::min;

long long c1, r1, c2, r2;

int main(void) {
	scanf("%lld%lld%lld%lld", & r1, & c1, & r2, & c2);
	if (r1 == r2 && c1 == c2) {
		puts("0");
		return 0;
	}
	if (llabs(r2 - r1) + llabs(c2 - c1) <= 3 || r1 + c1 == r2 + c2 || r1 - c1 == r2 - c2) {
		puts("1");
		return 0;
	}
	if ((llabs(r2 - r1) & 1) == (llabs(c2 - c1) & 1)) {
		puts("2");
		return 0;
	}
	else {
		long long deltay = llabs(c2 - c1), deltax = llabs(r2 - r1);
		if (min(llabs(r2 - deltay - r1), llabs(r2 + deltay - r1)) <= 3)
			puts("2");
		else if (min(llabs(c2 - deltax - c1), llabs(c2 + deltax - c1)) <= 3)
			puts("2");
		else
			puts("3");
	}
	return 0;
}


#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> P;
const int MAX = 200000;
int main(){
	int N,M,Q,op[MAX],p[MAX],A,B;
	bool rev=false;
	ll multX,multY,plusX,plusY,preM,preP,x,y;
	vector<int> q[MAX],index[MAX];
	vector<P> first;
	P xy[MAX];
	P ans[MAX];

	cin>>N;
	for(int i=0;i<N;i++)cin>>xy[i].first>>xy[i].second;
	cin>>M;
	for(int i=0;i<M;i++){
		cin>>op[i];
		if(op[i]>=3)cin>>p[i];
	}
	cin>>Q;
	for(int i=0;i<Q;i++){
		cin>>A>>B;A--;B--;
		if(A<0){
			ans[i]=xy[B];
		}else{
			q[A].push_back(B);
			index[A].push_back(i);
		}
	}
	multX=multY=1;
	plusX=plusY=0;
	for(int i=0;i<M;i++){
		preM=multX;
		preP=plusX;
		if(op[i]==1){
			rev=!rev;
			multX=multY;
			plusX=plusY;
			multY=-preM;
			plusY=-preP;
		}else if(op[i]==2){
			rev=!rev;
			multX=-multY;
			plusX=-plusY;
			multY=preM;
			plusY=preP;
		}else if(op[i]==3){
			multX*=-1;
			plusX*=-1;
			plusX+=2*p[i];
		}else if(op[i]==4){
			multY*=-1;
			plusY*=-1;
			plusY+=2*p[i];
		}
		for(int j=0;j<q[i].size();j++){
			if(rev){
				x=xy[q[i][j]].second;
				y=xy[q[i][j]].first;
			}else{
				x=xy[q[i][j]].first;
				y=xy[q[i][j]].second;
			}
			ans[index[i][j]]=P({plusX+multX*x,plusY+multY*y});
		}
	}
	for(int i=0;i<Q;i++){
		cout<<ans[i].first<<" "<<ans[i].second<<endl;
	}
	return 0;
}

#include <iostream>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <queue>
using namespace std;

using VI = vector <int>;
using VVI = vector <VI>;
using DI = deque <int>;
const int INF = 1000000000;
const int UNUSED = INF+1;

int solve(const VVI& adja, int f, int t) {
    int N = adja.size();
    VI dist(N, INF);
    DI que;
    dist[f] = 0;
    que.push_back(f);

    while (!que.empty()) {
        int now = que.front();
        que.pop_front();

        for  (int i = 0; i < adja[now].size(); ++i) {
            int nextv = adja[now][i];

            if (dist[nextv] == INF) {
                dist[nextv] = dist[now]+1;
                que.push_back(nextv);
            }
        }
    }

    return dist[t];
}

int solveDP(const VVI& CD, VVI& DP, int now, int st) {
    int &ret = DP[now][st];
    int K = CD.size();
    int tot = 1<<K;

    if (st == tot-1) {
        return ret = 0;
    }

    if (ret != UNUSED) {
        return ret;
    }

    ret = INF;

    for (int i = 0; i < K; ++i) {
        int nextv = 1<<i;

        if ((nextv&st) == 0 && CD[now][i] != INF) {
            ret = min(ret, CD[now][i] + solveDP(CD, DP, i, st|nextv));
        }
    }

    // cout << "DEBUG " << now << " " << st << " " << ret << endl;

    return ret;
}

int main() {
    int N;
    int M;

    cin >> N >> M;

    VI A(M);
    VI B(M);
    VVI adja(N);
    for (int i = 0; i < M; ++i) {
        cin >> A[i] >> B[i];
        --A[i];
        --B[i];
        adja[A[i]].push_back(B[i]);
        adja[B[i]].push_back(A[i]);
    }

    int K;
    cin >> K;
    VI C(K);

    for (int i = 0; i < K; ++i) {
        cin >> C[i];
        --C[i];
    }

    VVI CD(K, VI(K, INF));

    for (int i = 0; i < K; ++i) {
        CD[i][i] = 0;
        for (int j = i+1; j < K; ++j) {
            CD[i][j] = CD[j][i] = solve(adja, C[i], C[j]);
        }
    }

    int tot = 1<<K;
    int ans = INF;
    VVI DP(K, VI(tot, UNUSED));

    for (int i = 0; i < K; ++i) {
        solveDP(CD, DP, i, 1<<i);
    }

    for (int i = 0; i < K; ++i) {
        ans = min(ans, 1+DP[i][1<<i]);
    }

    if (ans >= INF) {
        cout << -1 << endl;
    } else {
        cout << ans << endl;
    }

    return 0;
}


#include<iostream>
#include<cctype>
using namespace std;
int main(void){
	char a,b;
	cin>>a>>b;
	cout<<(char)(a=='Y'?toupper(b):b)<<endl;
	return 0;
}

/** I can do this all day **/

#pragma GCC optimize("O2")
#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;
#define all(x)                      (x).begin(),(x).end()
#define F                           first
#define S                           second
#define Mp                          make_pair
#define SZ(x)			    		(int)x.size()
#define fast_io                     ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define file_io                     freopen("in.txt" , "r+" , stdin) ; freopen("out.txt" , "w+" , stdout);

const int N = 1e6 + 10;
const ll mod = 1e9 + 7;
const ll mod2 = 998244353;
const ll inf = 8e18;
const int LOG = 22;

ll pw(ll a , ll b, ll M)  { return (!b ? 1 : (b & 1 ? (a * pw(a * a % M, b / 2, M)) % M : pw(a * a % M, b / 2, M))); }

int main()
{
	int x, y;
	cin >> x >> y;
	if(x == y)
	{
		cout << x << endl;

	}
	else
	{
		if(x != 0 && y != 0) cout << 0 << endl;
		else if(x != 1 && y != 1) cout << 1 << endl;
		else cout << 2 << endl;
	}
    return 0;
}

/** test corner cases(n = 1?) watch for overflow or minus indices **/


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

int main(void){
  string str1,str2;
  int i;
  cin >> str1;
  str2 = "";
  for(i=0;i<str1.size();i++){
    if(str1.at(str1.size()-i-1) == '6')str2 += "9";
    else if(str1.at(str1.size()-i-1) == '9')str2 += "6";
    else str2 += str1.at(str1.size()-i-1);
  }
  cout << str2;
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    int n;
    cin >> n;
    int ans = n / 100;
    if ( n % 100 ) ans ++;
    cout << ans;
}


#include<bits/stdc++.h>
using namespace std;
# define ll long long
# define read read1<ll>()
# define Type template<typename T>
Type T read1(){
	T t=0;
	char k;
	bool vis=0;
	do (k=getchar())=='-'&&(vis=1);while('0'>k||k>'9');
	while('0'<=k&&k<='9')t=(t<<3)+(t<<1)+(k^'0'),k=getchar();
	return vis?-t:t;
}
# define fre(k) freopen(k".in","r",stdin);freopen(k".out","w",stdout)
pair<int,int>a[200005];
int s;
set<int,int>se;
int dis(int x,int y){return max(abs(a[x].first-a[y].first),abs(a[x].second-a[y].second));}
set<pair<int,pair<int,int> > >q2;
set<pair<int,int> >q,q1;
int main(){
	s=read;
	for(int i=1;i<=s;++i)a[i]=make_pair(read,read);
	sort(a+1,a+s+1);
	q.insert(make_pair(a[1].second,1));
	q.insert(make_pair(a[2].second,2));
	q1.insert(make_pair(-a[1].second,1));
	q1.insert(make_pair(-a[2].second,2));
	q2.insert(make_pair(dis(1,2),make_pair(1,2)));
	for(int i=3;i<=s;++i){
		q2.insert(make_pair(dis(1,i),make_pair(1,i)));
		q2.insert(make_pair(dis(2,i),make_pair(2,i)));
		auto j=q.begin();
		q2.insert(make_pair(dis(j->second,i),make_pair(j->second,i)));++j;
		q2.insert(make_pair(dis(j->second,i),make_pair(j->second,i)));j=q1.begin();
		q2.insert(make_pair(dis(j->second,i),make_pair(j->second,i)));++j;
		q2.insert(make_pair(dis(j->second,i),make_pair(j->second,i)));
		q.insert(make_pair(a[i].second,i));
		q1.insert(make_pair(-a[i].second,i));
		q.erase(q.begin());q1.erase(q1.begin());
	}auto i=q2.end();--i;--i;
	cout<<i->first;
	return 0;
}

#include<bits/stdc++.h>
#define dbug printf("I am here\n");
#define Fast ios_base::sync_with_stdio(false); cin.tie(0);
#define vs           v.size()
#define ss           s.size()
#define sz(a)       a.size()
#define sot(v)       sort(v.begin(),v.end())
#define all(v)       (v).begin(), (v).end()
#define rev(v)       reverse(v.begin(),v.end())
#define revsot(v)    sort(v.rbegin(),v.rend())
#define yes          cout<<"YES"<<endl
#define no           cout<<"NO"<<endl
#define ii           pair<int, int>
#define int          long long
#define ll           long long
#define ull          unsigned long long
#define pb           push_back
#define mpp          make_pair
#define Okay         0
#define pi           3.14159

const int mx = 2e6+100;
const int inf = 1e18;
const int mod = 1e9+7;
using namespace std;

void solve(){
    int n;
    cin>>n;
    int res = n/100;
    res++;
    cout<<res*100 - n <<endl;
}

int32_t main(){
    Fast;
//    int tst;
//    cin>>tst;
//    while(tst--)
    solve();
    return Okay;
}


#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <complex>
#include <queue>
#include <set>
#include <unordered_set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <iomanip>
#include <fstream>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int,int> p32;
typedef pair<ll,ll> p64;
typedef pair<double,double> pdd;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<vector<int> > vv32;
typedef vector<vector<ll> > vv64;
typedef vector<vector<p64> > vvp64;
typedef vector<p64> vp64;
typedef vector<p32> vp32;
ll MOD = 998244353;
double eps = 1e-12;
#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,s) for(ll i = s; i >= 0; i--)
#define rforsn(i,s,e) for(ll i = s; i >= e; i--)
#define ln "\n"
#define dbg(x) cout<<#x<<" = "<<x<<ln
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF 2e18
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())

void solve(){
   string s;
   cin>>s;
   for (int i = 0; i < s.size(); i++)
   {
       if(s[i]=='6'){
           s[i] ='9';
       }
       else if(s[i] == '9'){
           s[i] ='6';
       }

   }
   for (int i = s.size()-1; i >=0; i--)
   {
       cout<<s[i];
   }

}
int main()
{
    fast_cin();
    // ll t;
    // cin >> t;
    // for(int it=1;it<=t;it++) {
    //  cout << "Case #" << it+1 << ": ";
        solve();
    // }
    return 0;
}

#include "bits/stdc++.h"
using namespace std;
#define ll long long
const int areTests = 0;

string s;

void run_test(int testcase) {
	cin >> s;

	int ans = 0;
	for(int pin = 0; pin < 10000; pin++) {
		string str = to_string(pin);
		while(str.size() < 4) str = "0" + str;

		set <int> r;
		for(int i = 0; i < 10; i++) {
			if(s[i] == 'o') r.insert(i);
		}

		int ok = 1;
		for(char c: str) {
			if(s[c - '0'] == 'x') ok = 0;
			else if(s[c - '0'] == 'o') {
				r.erase(c - '0');
			}
		}
		if(ok && r.empty()) ans++;
	}
	cout << ans;
}

int main() {
	ios::sync_with_stdio(0);
	#ifndef LOCAL
	cin.tie(0);
	#endif
	cout << fixed << setprecision(10);

	int t = 1;
	if(areTests) cin >> t;
	for(int i = 1; i <= t; i++) {
		run_test(i);
	}
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;

#define all(v) v.begin(), v.end()

const ll mod=1000000007;

const string yesno(bool ans){
  return (ans?"Yes":"No");
}

int main() {
  int a,b;cin>>a>>b;
  int x,y;
  x=(a+b)/2;
  y=(a-b)/2;
  cout<<x<<" "<<y<<endl;
  return 0;
}

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

#define ll long long
#define pb push_back

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

    int a, b, suma = 0, sumb = 0;
    cin >> a >> b;

    while(a){
        suma += a % 10;
        a /= 10;
    }

    while(b){
        sumb += b % 10;
        b /= 10;
    }

    cout << max(suma, sumb);

    return 0;
}


#include <bits/stdc++.h>
// #include <boost/multiprecision/cpp_int.hpp>

#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,b,a) for(int i=b;i>=a;i--)
#define fori(a) for(auto i : a )
#define all(a) begin(a), end(a)
#define set(a,b) memset(a,b,sizeof(a))
#define sz(a) a.size()
double pi=acos(-1);
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PF push_front //deque
// #define mp make_pair
#define pq priority_queue
const ll mod=1000000007;
#define f first
#define s second
#define pii pair< ll, ll >
#define vi vector<int>
#define vpii vector<pii>
#define debug(v) for(auto i:v) cout<<i<<" ";
#define tc int t; cin >> t; while(t--)

// using namespace boost::multiprecision;
using namespace std;
void optimizeIO(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}

const int N=1000005;
ll fact[N],invfact[N];
ll power(ll x,ll y){
  if(y<=0) return 1LL;
  ll z=power(x,y/2);
  if(y%2) return (((z*z)%mod)*x)%mod;
  return (z*z)%mod;
}

void pre(){
  fact[0]=invfact[0]=invfact[1]=fact[1]=1;
  rep(i,2,N) fact[i]=(i*fact[i-1])%mod;
  rep(i,2,N) invfact[i]=(invfact[i-1]*power(i,mod-2))%mod;
}
ll nCr(ll n,ll k){ return (((fact[n]*invfact[n-k])%mod)*invfact[k])%mod; }

const int N1=1e6+1;
vector<int> isprime(N1,1),prime;
void seive(){
  rep(i,2,sqrt(N1)+1){
      if(isprime[i]){
        for(int j=i*i;j<N1;j+=i) isprime[j]=0;
        prime.pb(i);
      }
  }
  rep(i,sqrt(N1)+1,N1) if(isprime[i]) prime.pb(i);
}

struct dsu {
    vector<int> par, rank;
    dsu(int n): par(n+1), rank(n+1) {
        for (int i = 0; i <= n; i++) {
            par[i] = i;
            rank[i]= 1;
        }
    }
    int root(int a) {
        if (a == par[a]) return a;
        return par[a] = root(par[a]);
    }
    void merge(int a, int b) {
        a = root(a);
        b = root(b);
        if (a == b) return;
        if (rank[a] > rank[b]) swap(a, b);
        par[b] = a;
    }
    set<int> parent(int n){
        set<int> s;
        for(int i=1;i<=n;i++){
            s.insert(root(i));
        }
        return s;
    }
};

void solve(){
  int n;
  cin>>n;
  int a[n],b[n];
  rep(i,0,n){cin>>a[i]; b[i]=0;}
  rep(i,0,n) b[a[i]-1]++;
  int flag=0;
  rep(i,0,n){
    if(b[i]==0 || b[i]>1) flag=1;
  }
  if(flag) cout<<"No";
  else cout<<"Yes";
}

int main(){
    optimizeIO();
    int r=1;
    {solve();}
}

#include<bits/stdc++.h>
#define int long long
#define rep(i,a,b) for(register int i=(a);i<=(b);i++)
#define per(i,a,b) for(register int i=(a);i>=(b);i--)
using namespace std;
const int N=2009,inf=0x3f3f3f3f3f3f3f3f;

inline int read() {
    register int x=0, f=1; register char c=getchar();
    while(c<'0'||c>'9') {if(c=='-') f=-1; c=getchar();}
    while(c>='0'&&c<='9') {x=(x<<3)+(x<<1)+c-48,c=getchar();}
    return x*f;
}

int n,m,a[N],b[N],c[N],d[N];
bool vst[N];
struct edge {int to,w;};
vector<edge>e[N];
struct node {
	int u,w;
	bool operator < (const node &b) const {
		return w>b.w;
	}
};
void dijakstra(int s) {
	priority_queue<node>q; q.push((node){s,0});
	memset(d,0x3f,sizeof(d)); d[s]=0;
	memset(vst,0,sizeof(vst));
	while(!q.empty()) {
		int u=q.top().u; q.pop();
		if(vst[u]) continue; vst[u]=1;
		for(auto ed:e[u])
			if(d[ed.to]>d[u]+ed.w)
				d[ed.to]=d[u]+ed.w, q.push((node){ed.to,d[ed.to]});
	}
}

signed main() {
	n=read(), m=read();
	rep(i,1,m) a[i]=read(), b[i]=read(), c[i]=read();
	rep(i,1,n) {
		rep(j,1,n) e[j].clear();
		rep(j,1,m) {
			if(b[j]==i) e[a[j]].push_back((edge){n+1,c[j]});
			else e[a[j]].push_back((edge){b[j],c[j]});
		}
		dijakstra(i);
		printf("%lld\n",d[n+1]<inf?d[n+1]:-1ll);
	}
	return 0;
}


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

int main(){
  string S;
  cin >> S;
  char s=S.at(0);
  string Sback=S.substr(1);
  cout << Sback+s << endl;
}

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
typedef long long int ll;
int main(){
	string s;
	cin>>s;
	reverse(s.begin(),s.end());
	for(int i=0;i<s.length();i++){
		if(s[i]=='6'){
			s[i]='9';
		}
		else if(s[i]=='9'){
			s[i]='6';
		}
	}
	cout<<s<<endl;
	return 0;
}


#include <bits/stdc++.h>

int main(){
    int N, M;
    std::cin >> N >> M;
    std::vector< std::vector< int > > AB(N);
    std::map< int, int > cost;
    for(int i=0; i<M; i++){
        int a, b, c;
        std::cin >> a >> b >> c;
        a--;
        b--;
        int ab = a * N + b;
        auto itr = cost.find(ab);
        if(itr == cost.end()){
            AB[a].push_back(b);
            cost[ab] = c;
        }else if(c < itr->second){
            cost[ab] = c;
        }
    }

    for(int i=0; i<N; i++){
        std::priority_queue< std::pair< int, int >, std::vector<std::pair< int, int >>, std::greater<std::pair< int, int >> > time_pos;

        std::pair< int, int > tmp;
        tmp.first = 0;
        tmp.second = i;
        time_pos.push(tmp);
        std::vector< int > min(N, 1e9);

        while(!time_pos.empty()){
            tmp = time_pos.top(); time_pos.pop();
            int c_pos = tmp.second;
            int c_time = tmp.first;

            if(c_time >= min[c_pos]){
                continue;
            }

            if(c_time != 0){
                min[c_pos] = c_time;
            }

            for(int j=0; j<AB[c_pos].size(); j++){
                tmp.second = AB[c_pos][j];
                tmp.first = c_time + cost[c_pos * N + AB[c_pos][j]];
                if(tmp.first >= min[AB[c_pos][j]]){
                    continue;
                }
                time_pos.push(tmp);
            }
        }

        if(min[i] != 1e9){
            std::cout << min[i] << std::endl;
        }else{
            std::cout << -1 << std::endl;
        }

    }

    return 0;
}

#include <bits/stdc++.h>
#define pi 3.14159
using namespace std;
typedef long long LL;
const LL MOD = 1e9 + 7;
const int N = 1e5 + 7, M = 1e7, OO = 0x3f3f3f3f;
#define AC ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); cin.sync_with_stdio(0);
int main()
{
    LL n,m,t,flag=1,last=0,cap;
    cin>>n>>m>>t;
    cap=n;
    while(m--){
        LL arrive,stay;
        cin>>arrive>>stay;
        LL dis=arrive-last;
        n-=dis;
        if(n<=0){
            flag=0;
        }
        n+=stay-arrive;
        n=min(n,cap);
        last=stay;
    }
    LL dis=t-last;
    n-=dis;
    if(n<=0){
        flag=0;
    }
    if (flag){
        cout<<"Yes";
    }
    else{
        cout<<"No";
    }

    return 0;
}


#include "bits/stdc++.h"

using namespace std;
using ll = long long;

void Main() {
    double A, B, W;
    cin >> A >> B >> W;
    W *= 1000;

    double minimum = W / B;
    double maximum = W / A;

    bool foundMin = false;
    bool foundMax = false;
    int minInt = 1000000000;
    int maxInt = -1;
    for (int i = 1; i < 1001000; ++i) {
        if (minimum <= i && i <= maximum) {
            minInt = min(minInt, i);
            maxInt = max(maxInt, i);
        }
    }
    if (maxInt < 0) {
        cout << "UNSATISFIABLE" << endl;
    }
    else {
        cout << minInt << " " << maxInt << endl;
    }
}

int main() {
    std::cout << std::fixed << std::setprecision(15);
    Main();
    return 0;
}

/*
   Author   : MatsuTaku
   Date     : 02/18/21
*/

#include <bits/stdc++.h>
using namespace std;
#include <x86intrin.h>
#ifndef ONLINE_JUDGE
#define Assert(cond)      assert(cond)
#else
#define Assert(cond)
#endif
#define rep(i, n)         for (size_t i = 0, i##_len = (n); i < i##_len; i++)
using lint = long long int;
template<typename T>
using vvec = vector<vector<T>>;
template<typename T>
vvec<T> make_vvec(int n, int m, T v) { return vvec<T>(n, vector<T>(m, v)); }
template<typename T>
void chmax(T& dst, T x) { dst = max(dst, x); }
template<typename T>
void chmin(T& dst, T x) { dst = min(dst, x); }

class Solver {
 public:
  Solver();
  void solve();
};

Solver::Solver() {}

constexpr lint scale = 10000;
void Solver::solve() {
  double _x,_y,_r; cin>>_x>>_y>>_r;
  lint x = (lint) round(_x*scale);
  lint y = (lint) round(_y*scale);
  lint r = (lint) round(_r*scale);
  lint p = (x-r)/scale * scale;
  lint ans = 0;
  while (p <= x+r) {
    if (p < x-r) {
      p += scale;
      continue;
    }
    lint dx = abs(x-p);
    lint dy = sqrt(r*r-dx*dx);
//    while ((dy+1)*(dy+1) + dx*dx <= r*r) dy++;
    while (dy*dy + dx*dx > r*r) dy--;
    lint by = y - dy - 1, ty = y + dy;
    if (by < 0) {
      lint add = (-by/scale+1) * scale;
      by += add;
      ty += add;
    }
    ty /= scale;
    by /= scale;
    ans += ty-by;
    p += scale;
  }
  cout << ans << endl;
}

int main() {
  cin.tie(nullptr); ios::sync_with_stdio(false);
  cout<<fixed<<setprecision(10);
  Solver solver;
  int t = 1;
//  cin>>t;
  while (t--) {
    solver.solve();
  }
  return 0;
}