#include <iostream>
#include <stdio.h>
#include <math.h>

//I は1, V は5, X は10, L は50, C は100, D は500, M は1000,

#define I 1
#define V 5
#define X 10
#define L 50
#define C 100
#define D 500
#define M 1000

using namespace std;

int main(){

	string str;
	while(cin>>str){
		int data[200];
		int sum = 0;

		//データの数値化
		for(int i=0;i<str.size();i++){
			switch(str[i]){
				case 'I':
					data[i]=I;
					break;
				case 'V':
					data[i]=V;
					break;
				case 'X':
					data[i]=X;
					break;
				case 'L':
					data[i]=L;
					break;
				case 'C':
					data[i]=C;
					break;
				case 'D':
					data[i]=D;
					break;
				case 'M':
					data[i]=M;
					break;
			}
		}

		for(int i=0;i<str.size();i++){
			if(i==str.size()-1){
				sum+=data[i];
			}
			else{
				if(data[i]<data[i+1]){
					sum+= (data[i+1]-data[i]);
					i++;
				}
				else{
					sum+=data[i];
				}
			}
		}

		cout<<sum<<endl;
	}

	return 0;

}

/*
IV
CCCCLXXXXVIIII
CDXCIX
*/

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

vector<int> a;
vector<string> b(4);
string st;

bool dfs(int i, int sum, int n) {

	if (i == 0) {
		sum = sum + a[0];
		i++;
	}

	if (i == n) {
		if (sum == 7) {
			for (int j = 0; j < n; j++) {
				if (j == 0) {
					cout << st[j];
					continue;
				}
				cout << b[j] << st[j];
			}
			cout << "=" << sum << endl;
			return true;
		}
		else{
			return false;
        }
    }

	b[i] = "+";
	if (dfs(i + 1, sum + a[i], n)) return true;

	b[i] = "-";
	if (dfs(i + 1, sum - a[i], n)) return true;

    return false;
}

int main(void) {

	cin >> st;
	for (int i = 0; i < 4; i++)
		a.push_back(st[i] - '0');

	bool a = dfs(0, 0, 4);

}


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

typedef pair<int, char> P;
#define fs first
#define sc second

int main(){
    int N, Q;
    string s;
    cin >> N >> s >> Q;

    vector<ll> ans;
    for(int i = 0; i < Q; i++){
        int k;
        cin >> k;

        ll cntD = 0;
        ll cntM = 0;
        ll cntDM = 0;
        ll res = 0;
        deque<P> que;
        for(int j = 0; j < N; j++){
            //余分なものをpop
            while(true){
                if(que.size() == 0) break;
                else if(que.back().sc == 'D' && que.back().fs > j - k) break;
                else if(que.back().sc == 'M'){
                    //cout << "popM" << endl;
                    cntM--;
                    que.pop_back();
                }
                else if(que.back().sc == 'D' && que.back().fs <= j - k){
                    //cout << "popD" << endl;
                    cntD--;
                    cntDM -= cntM;
                    que.pop_back();
                }
            }

            if(s[j] == 'D'){
                //cout << "pushD" << endl;
                que.push_front(P(j, 'D'));
                cntD++;
            }

            else if(s[j] == 'M'){
                //cout << "pushM" << endl;
                que.push_front(P(j, 'M'));
                cntM++;
                cntDM += cntD;
            }

            else if(s[j] == 'C'){
                //cout << "pushC" << endl;
                res += cntDM;
            }

            //printf("j = %2d  cntD = %2d  cntM = %2d  cntDM = %2d\n", j, cntD, cntM, cntDM);
        }

        ans.push_back(res);
    }

    for(ll v : ans){
        cout << v << endl;
    }

    return 0;
}

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <limits>
#include <queue>
#include <iomanip>
#include <set>

template<typename T> bool chmax(T &a,T b){
    if(a<b){
        a=b;
        return true;
    }
    return false;
}

template<typename T> bool chmin(T &a,T b){
    if(a>b){
        a=b;
        return true;
    }
    return false;
}

using namespace std;
#define ALL(X) X.begin(),X.end()
using ll = long long int;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<vvll> vvvll;
const int MOD=1000000007;
//const int MOD=998244353;
const int INTMAX=1001001000;
const ll LLMAX=1010010010010010000;

void ptn(vector<vector<bool>> &ans,ll i,ll j,ll p){
    if(p==1){
        ans[i*4][j*4]=1;ans[i*4+1][j*4]=1;ans[i*4+2][j*4]=1;
        ans[i*4][j*4+1]=1;ans[i*4+2][j*4+1]=1;
        ans[i*4][j*4+2]=1;ans[i*4+1][j*4+2]=1;ans[i*4+2][j*4+2]=1;
    }
    if(p==2){
        ans[i*4+1][j*4+1]=1;
    }
}

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

    ll A,B;
    cin>>A>>B;

    bool bo=(A>B);
    if(bo){
        ll tmp=A;
        A=B;
        B=tmp;
    }

    vector<vector<bool>> ans(100,vector<bool>(100,0));

    if(A<=B){
        ll count=0;
        for(ll i=0;i<100;i++){
            for(ll j=0;j<100;j++){
                ptn(ans,i,j,3);
            }
        }
        for(ll i=0;i<A-1;i++){
            ptn(ans,count/25,count%25,1);
            count++;
        }
        for(ll i=0;i<B-A+1;i++){
            ptn(ans,count/25,count%25,2);
            count++;
        }
    }

    printf("100 100\n");
    for(ll i=0;i<100;i++){
        for(ll j=0;j<100;j++){
            if((ans[i][j]==1 && !bo) || (ans[i][j]==0 && bo)) printf("#");
            else printf(".");
        }
        printf("\n");
    }

    return 0;
}


#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <functional>
#include <algorithm>
#include <climits>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long int
#define rep(i,n) for( int i = 0; i < n; i++ )
#define rrep(i,n) for( int i = n; i >= 0; i-- )
#define REP(i,s,t) for( int i = s; i <= t; i++ )
#define RREP(i,s,t) for( int i = s; i >= t; i-- )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 1000000000000000000

int main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N; cin >> N;
    int A[200010];
    rep(i, N) cin >> A[i];
    ll ans = 0;
    int height = 0;
    rep(i, N) {
        height = max(height, A[i]);
        ans += height - A[i];
    }
    cout << ans << endl;

    return 0;
}

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <bitset>

typedef unsigned long long ULLONG;
typedef long long LLONG;
static const LLONG MOD_NUM = 1000000007; //998244353;

template<class _T> static void get(_T& a) {
	std::cin >> a;
}
template<class _T> static void get(_T& a, _T& b) {
	std::cin >> a >> b;
}
template<class _T> static void get(_T& a, _T& b, _T& c) {
	std::cin >> a >> b >> c;
}

static void exec();

int main()
{
	exec();
	fflush(stdout);
	return 0;
}

static void exec()
{
	int N;
	get(N);

	std::vector<std::pair<LLONG, LLONG>> plate(N);
	for (int i = 0; i < N; i++) {
		get(plate[i].first, plate[i].second);
	}

	auto psum = [](const std::pair<LLONG, LLONG>& a, const std::pair<LLONG, LLONG>& b) {
		return (a.first + a.second) > (b.first + b.second);
	};
	std::sort(plate.begin(), plate.end(), psum);

	LLONG tak = 0, aok = 0;
	for (int i = 0; i < N; i++) {
		if (i % 2) {
			aok += plate[i].second;
		}
		else {
			tak += plate[i].first;
		}
	}
	printf("%lld\n", tak - aok);
}


#include <iostream>
#include <algorithm>

using namespace std;

void solve() {
    int n;
    long long t1, t2, ans, t;
    ans = 0;
    cin >> n >> t;
    cin >> t1;
    t1 = t2 = 0;
    for (int i=1;i<n; ++i) {
        cin >> t1;
        ans += min(t1 - t2, t);
        t2 = t1;
    }
    ans += t;
    cout << ans;

}

int main() {

    solve();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define rep(i, n) FOR(i, 0, n)
#define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; --i)
#define whole(x) (x).begin(),(x).end()
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())
using P = pair<int, int>;
#define debug(var) cerr << "[" << #var << "] " << var << endl
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
const ll mod = 1000000007;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,-1,0,1};

int main(){
    ll n, T;
    cin >> n >> T;
    vector<ll> t(n);
    rep(i, n) cin >> t[i];
    ll ans = T*n;
    rep(i, n-1) {
        ans -= max(0LL, t[i]+T-t[i+1]);
    }

    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
#include<unordered_set>
#include<unordered_map>
#include <algorithm>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
#define ll long long
#define rep(i,n) for (ll i = 0; i < (n); i++)
#define FOR(i,a,b) for(ll i=(a);i<(b);i++)
#define FORR(i,a,b)for(ll i=(a);i<=(b);i++)
#define repR(i,n) for(ll i=n;i>=0;i--)
#define all(v)(v).begin(),(v).end()
#define rall(v)(v).rbegin(),(v).rend()
#define F first
#define S second
#define pb push_back
#define pu push
#define COUT(x) cout<<(x)<<"\n"
#define PQ priority_queue<ll>
#define PQR priority_queue<ll,vector<ll>,greater<ll>>
#define YES(n) cout << ((n) ? "YES\n" : "NO\n"  )
#define Yes(n) cout << ((n) ? "Yes\n" : "No\n"  )
#define mp make_pair
#define sz(x) (ll)(x).size()
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef tuple<ll,ll,ll> tll;
const ll MOD = 1000000007LL;
const ll INF = 1LL << 60;
using vll = vector<ll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvll = vector<vll>;
using vstr = vector<string>;
using vc = vector<char>;
using vvc = vector<vc>;
template<class T> inline bool chmax(T& a, T b) {
 if (a < b) { a = b; return true; } return false;
}
template<class T> inline bool chmin(T& a, T b) {
 if (a > b) { a = b; return true; } return false;
}
ll dx[4]={0,1,0,-1};
ll dy[4]={1,0,-1,0};
int main(){
  string s;
  cin>>s;
  ll n=sz(s);
  vvll dp(n+1,vll(2,INF));
  dp[0][0]=0;
  reverse(all(s));
  rep(i,n)rep(j,2){
    if(dp[i][j]==INF) continue;
    ll c=s[i]-'0';
    ll no=10-c;
    if(j==0){
      chmin(dp[i+1][0],dp[i][j]+c);
      chmin(dp[i+1][1],dp[i][j]+no);
    }
    else{
      chmin(dp[i+1][0],dp[i][j]+1+c);
      chmin(dp[i+1][1],dp[i][j]+no-1);
    }
  }
  COUT(min(dp[n][0],dp[n][1]+1LL));
}

#include <iostream>
#include <string>
int main(){
  char s[10];
  for (int i = 0; i < 10; i++){
    std::cin >> s[i];
    if (i == 3){
      s[i] = '8';
    }
  }

  for (int i = 0; i < 10; i++){
    std::cout << s[i];
  }
  std::cout << std::endl;
  return 0;
}


#include <stdio.h>
const int N=110;
const int INF=1<<30;
int min(int a,int b){
    return a>b?b:a;
}
int main(){
    int n,dp[N][N],a[N];
    scanf("%d%d%d",&n,&a[0],&a[1]);
    for(int i=1;i<n;i++)scanf("%d%d",&a[i],&a[i+1]);
    for(int k=1;k<n;k++){
        for(int i=0;i<n-k;i++){
            dp[i][i+k]=INF;
            for(int j=i;j<i+k;j++)dp[i][i+k]=min(dp[i][i+k],dp[i][j]+dp[j+1][i+k]+a[i]*a[j+1]*a[i+k+1]);
        }
    }
    printf("%d\n",dp[0][n-1]);
}

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

int main(){

  int H, W, i, j, k;
  cin >> H >> W;
  vector<vector<char>> A(H, vector<char>(W));
  vector<int> dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
  queue<P> nxs;

  int cnt_sn = 0; //シャープの数
  int cnt_fn = 0; //フェイズ内の要素の数
  int cnt    = 0; // フェイズの数
  for(i = 0; i < H; i++){
    for(j = 0; j < W; j++){
      cin >> A.at(i).at(j);
      if(A.at(i).at(j) == '#'){
        nxs.push(P(i, j));
        cnt_sn++;
      }
    }
  }

  while(nxs.size() != 0 && cnt_sn < W * H){

    if(cnt_fn == 0){
      cnt++; cnt_fn = nxs.size();
    }
    P pos = nxs.front(); nxs.pop();
    for(i = 0; i < 4; i++){
      int x = pos.second + dx.at(i), y = pos.first + dy.at(i);
      if(x >= 0 && y >= 0 && x < W && y < H){
        if(A.at(y).at(x) == '.'){
          A.at(y).at(x) = '#';
          cnt_sn++;
          nxs.push(P(y, x));
        }
      }
    }
    cnt_fn--;
  }

  cout << cnt << endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define Mid ((l+r)/2)
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define drep(i,a,b) for(int i=(a);i>=(b);--i)
#define file(a) freopen(#a".in","r",stdin),freopen(#a".out","w",stdout);
const int maxn=2e3+5,mod=1e9+7,inf=0x3f3f3f3f;
int n,m,Q,K,T;
int read(){
    int x=0,f=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}char c[maxn];
bool a[maxn][maxn];
bool b[maxn][maxn];
int pre[maxn][maxn];
int stk[maxn],top;
int h[maxn];
signed main(){
    //file(a);
    n=read();m=read();
    rep(i,1,n){
        scanf("%s",c+1);
        rep(j,1,m)a[i][j]=(c[j]=='.');
    }
    rep(i,1,n-1)rep(j,1,m-1){
        int cnt=0;
        rep(ii,i,i+1)rep(jj,j,j+1)cnt+=a[ii][jj];
        b[i][j]=(!(cnt&1));
    }
    rep(j,1,m-1){
        int now=1;
        rep(i,1,n-1){
            if(b[i][j]!=b[now][j])now=i;
            pre[i][j]=now;
        }
    }int ans=0;
    rep(i,1,n-1){
        rep(j,1,m-1)h[j]=i-pre[i][j]+1;
        stk[0]=0;stk[top=1]=1;
        rep(j,2,m){
            if(b[i][j]!=b[i][j-1]||j>=m){
                while(top){
                    int x=j-stk[top-1]-1,y=h[stk[top]];
                    ans=max(ans,(x+1)*(y+1));--top;
                }stk[0]=j-1,stk[top=1]=j;continue;
            }
            while(top&&h[stk[top]]>=h[j]){
                int x=j-stk[top-1]-1,y=h[stk[top]];
                ans=max(ans,(x+1)*(y+1));--top;
            }stk[++top]=j;
        }
    }printf("%d\n",(max(ans,max(n,m))));

    return 0;
}

#include<cstdio>
#include<cctype>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define id(a,b) (a*n-n+b)
#define reg register
typedef long long ll;
template<typename T>inline T read(){
    reg T x=0;reg short f=1;reg char c=getchar();
    for(;!isdigit(c);f=c=='-'?-1:1,c=getchar());
    for(;isdigit(c);x=x*10+(c^48),c=getchar());
    return x*f;
}
const int inf=0x3f3f3f3f;
int n,m,h[2005],stk[2005];
bool mp[2005][2005],a[2005][2005];
int main(){
	n=read<int>();m=read<int>();reg int ans=max(n,m);
	for(reg int i=1;i<=n;i++)
		for(reg int j=1;j<=m;j++){
			reg char ch=getchar();
			while(ch!='#'&&ch!='.')ch=getchar();
			mp[i][j]=(ch=='#');
		}
	for(reg int i=1;i<n;i++)
		for(reg int j=1;j<m;j++){
			reg int cnt=(mp[i][j]+mp[i+1][j]+mp[i][j+1]+mp[i+1][j+1])&1;
			if(!cnt)a[i][j]=1;
		}
	for(reg int i=1;i<=n;i++){
		reg int top=0;
		for(reg int j=1;j<m;j++)h[j]=(a[i][j]?h[j]+1:0);
		for(reg int j=1;j<=m;j++){
			while(top&&h[j]<h[stk[top]])
				ans=max(ans,(j-stk[top-1])*(h[stk[top]]+1)),top--;
			stk[++top]=j;
		}
	}
	printf("%d\n",ans);
	return 0;
}


#include "bits/stdc++.h"
#define fio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define endl '\n'
#define all(V) (V).begin(), (V).end()
using namespace std;
typedef long long ll;

int main() {fio;
	string s;
	cin >> s;
	vector <int> cnt(26, 0);
	ll sm = 0, ans = 0;
	for(int i = 0; i < 26; i++) {
		cnt[i] = count(all(s), 'a' + i);
		ans += sm * cnt[i];
		sm += cnt[i];
	}
	cout << ans + 1 << endl;
    return 0;
}

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <stdio.h>
#include <queue>
#include <deque>
#include <cstdio>
#include <set>
#include <map>
#include <bitset>
#include <stack>
#include <cctype>
using namespace std;
long long co[26] = { 0 };
int main() {
	string s;
	cin >> s;
	long long n = s.size();
	for (int i = 0; i < n; i++) {
		co[int(s[i] - 'a')]++;
	}
	long long ans = n * (n - 1) / 2 + 1;
	for (int j = 0; j < 26; j++) {
		if (co[j] >= 2) {
			ans -= co[j] * (co[j] - 1) / 2;
		}
	}
	cout << ans << endl;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#define ll long long
using namespace std;
const int N=200005;

inline int read(){
    int x=0; char ch=getchar();
    for(;!isdigit(ch);ch=getchar());
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    return x;
}

int n,px,py;
ll a[N],ans=1e18,tot,now,mx,mn;

inline void update(){
    if(now<mn) mn=now;
    else if(now>mx) mx=now;
}

inline void solve(){
    for(int i=1;i<=n;i++){
        while(px<i&&a[px+1]*2ll<=a[i]) px++;
        while(py<n&&a[py+1]*2ll<=tot+a[i]) py++;

        for(int u=px+1;u>=px;u--)
            for(int v=py+1;v>=py;v--){
                mx=mn=a[u];

                now=a[i]-a[u],update();
                now=a[v]-a[i],update();
                now=tot-a[v],update();

                ans=min(ans,mx-mn);
            }
    }
}

int main(){
    n=read();
    for(int i=1;i<=n;i++) a[i]=a[i-1]+(ll)read();
    a[n+1]=a[n+2]=tot=a[n];
    solve(),printf("%lld\n",ans);
    return 0;
}

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>

using namespace std;
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag,
             tree_order_statistics_node_update>
    policy_set;

#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (ll)(x).size()
#define fill(a)  memset(a, 0, sizeof (a))
#define ALL(c) c.begin(),c.end()
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
typedef long double ld;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;

void preprocess(){

}
const ll N=3e5+7;
const ll INF=1e18+1;
const ll MOD=1e9+7;
//Have to ramp up more on implementation skillz to do it fast,
// and debug skillz, it is not as easy as you think with two pointers
ll n,a[N],pref[N];
ll f(ll l1,ll r1,ll l2, ll r2){
    return abs((pref[r1]-pref[l1-1])-(pref[r2]-pref[l2-1]));
}
// So we will implement the two pointer solution to this also
// very well
// So in ternary search we always need to check 4 values near, the start,end
// like in that cf problem, no need to do this all over again
ll find_left(ll i){
    ll start=1,end=i-1;
    while(start<=end){
        ll mid1=(2*start+end)/3,mid2=(start+2*end)/3;
        // cout<<start<<" "<<mid1<<" "<<mid2<<" "<<end<<"\n";
        if(f(1,mid1,mid1+1,i)>f(1,mid2,mid2+1,i))
            start=mid1+1;
        else
            end=mid2-1;
    }
        // cout<<start<<" "<<end<<"\n";
    ll arr[]={start,end},ans=1e18,ansidx=start;
    for(ll j=0;j<2;j++)
        for(ll jj=-1;jj<=1;jj++){
            ll idx=arr[j]+jj;
            if(idx<1 || idx>i-1)continue;
            if(ans>f(1,idx,idx+1,i))ans=f(1,idx,idx+1,i),ansidx=idx;
        }

    return ansidx;
}
// I remember facing this problem before
ll find_right(ll i){
    ll start=i+1,end=n-1;
    while(start<=end){
        ll mid1=(2*start+end)/3,mid2=(start+2*end)/3;
        if(f(i+1,mid1,mid1+1,n)>f(i+1,mid2,mid2+1,n))
            start=mid1+1;
        else
            end=mid2-1;
    }

    ll arr[]={start,end},ans=1e18,ansidx=start;
    for(ll j=0;j<2;j++)
        for(ll jj=-1;jj<=1;jj++){
            ll idx=arr[j]+jj;
            if(idx<i+1 || idx>n)continue;
            if(ans>f(i+1,idx,idx+1,n))ans=f(i+1,idx,idx+1,n),ansidx=idx;
        }
    return ansidx;
}
void solve(){
    cin>>n;
    for(ll i=1;i<=n;i++)cin>>a[i],pref[i]=pref[i-1]+a[i];
    ll ans=INT64_MAX;
    // cout<<find_left(4)<<" "<<f(1,1,2,4)<<" "<<f(1,2,3,4)<<" "<<f(1,3,4,4)<<"\n";
    // return;
    for(ll i=1;i<=n;i++){
        //i ins the middle split, in this case
        // 1..left left+1..i i+1..right right+1..n
        ll left=find_left(i),right=find_right(i);
        // cout<<left<<" "<<right<<"\n";
        vector<ll> vecs({pref[left],pref[i]-pref[left],pref[right]-pref[i],pref[n]-pref[right]});
        sort(all(vecs));
        ans=min(ans,vecs.back()-vecs[0]);
    }
    cout<<ans<<"\n";
}
int main() {
	// #ifndef ONLINE_JUDGE
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	// #endif
	cin.sync_with_stdio(0); cin.tie(0);
	cin.exceptions(cin.failbit);
	preprocess();
	int t=1;
	//cin>>t;
	//cout<<t<<endl;
	for(int i=0;i<t;i++)
		solve();
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define REP(i,a,b) for(int i=a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)
#define all(c) (c).begin(), (c).end()
#define zero(a) memset(a, 0, sizeof a)
#define minus(a) memset(a, -1, sizeof a)
#define watch(a) { std::cout << #a << " = " << a << "\n"; }
template<class T1, class T2> inline bool minimize(T1 &a, T2 b) { return b < a && (a = b, 1); }
template<class T1, class T2> inline bool maximize(T1 &a, T2 b) { return a < b && (a = b, 1); }
template<class T, class V> istream& operator>> (istream& ist, pair<T, V>& p) { return ist >> p.first >> p.second; }
template<class T> ostream& operator<< (ostream& ost, pair<T, T>& p) { return ost << p.first << ", " << p.second; }
template<class T> istream& operator>> (istream& ist, vector<T>& vs) { for(auto& e: vs) ist >> e; return ist; }

typedef long long ll;
int const inf = INT_MAX / 2;

int main() {
  int N; cin >> N;
  vector<int> ab;
  ll sum = 0;
  rep(i, N) {
    int a, b; cin >> a >> b;
    ab.push_back(a + b);
    sum -= b;
  }
  sort(ab.rbegin(), ab.rend());
  for (int i = 0; i < N; i += 2) {
    sum += ab[i];
  }
  cout << sum << "\n";
}

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <sstream>
#include <string>
#include <utility>
#include <map>
#include <memory>
#include <set>
#include <vector>
#include <deque>
#include <list>
#include <stack>
#include <queue>

using namespace std;

class MCMult
{
public:
  vector<vector<int>> mat;
  int solve();
};

int MCMult::solve()
{
  int ms = mat.size();
  vector<vector<int>> dp(ms, vector<int>(ms, 0));

  for ( auto i = 0; i < ms - 1; ++i )
    dp[i][i+1] = mat[i][0] * mat[i][1] * mat[i+1][1];

  for ( auto k = 2; k < ms; ++k )
    {
      for ( auto i = 0; i + k < ms; ++i )
        {
          int ret = dp[i+1][i+k] + mat[i][0] * mat[i][1] * mat[i+k][1];
          ret = min( ret, dp[i][i+k-1] + mat[i+k][0] * mat[i+k][1] * mat[i][0]);

          for ( auto j = i + 1; j < i + k - 1; ++j )
            {
              ret = min( ret, dp[i][j] + dp[j+1][i+k] + mat[i][0] * mat[j][1] * mat[i+k][1]);
            }
          dp[i][i+k] = ret;
        }
    }

  cout << dp[0][ms-1] << endl;

  return 0;
}

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

  MCMult m;

  for ( int i = 0; i < n; ++i )
    {
      int x;
      vector<int> v;

      cin >> x;
      v.push_back( x );
      cin >> x;
      v.push_back( x );

      m.mat.push_back( v );
    }

  m.solve();

  return 0;
}


#include <iostream>

using namespace std;

int main(){
    int n,team1,team2,Point[101],po1,po2,cnt;

    for( int i = 0 ; i < 101 ; i++ ) Point[i] = 0;

    cin >> n;
    for( int i = 0; i < n*(n-1)/2 ; i++ ){

	cin >> team1 >> team2 >> po1 >> po2;
	if( po1 > po2 ) Point[team1] += 3;
	else if( po1 < po2 ) Point[team2] += 3;
	else{
	    Point[team1]++; Point[team2]++;
	}
    }

    for( int i = 1 ; i <= n ; i++ ){
	cnt = 1;
	for( int j = 1 ; j <= n ; j++ ){
	    if( Point[i] < Point[j] ) cnt++;
	}
	cout << cnt << endl;
    }
    return 0;
}


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

int main() {
int N,K,sum;
  sum = 0;
  cin >> N >> K;
vector<int> vec(N);
for (int i = 0; i < N; i++) {
  cin >> vec.at(i);
}
sort(vec.begin(), vec.end());
for (int i = 0; i < K; i++){
  sum += vec.at(N-1);
  N --;
}
  cout << sum << endl;

}

#include <iostream>
#include <stdio.h>
#include <vector>
#include <math.h>
using namespace std;

int main(void) {
    double a,b; cin >> a >> b;
    int sum = 0;
    int i = 0;
    while (i < 2) {
        if (a > b) {
            sum += a;
            a--;
        } else {
            sum += b;
            b--;
        }
        i++;
    }
    cout << sum << endl;
}


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define RFOR(i,a,b) for (int i=(b)-1;i>=(a);i--)
#define REP(i,n) for (int i=0;i<(n);i++)
#define RREP(i,n) for (int i=(n)-1;i>=0;i--)

const int MAX = 1000000;

int main() {
    string str;
    getline(cin, str);
    int j=0, o=0, i=0;
    int ans = 0;
    REP(t, str.length()) {
        if (str[t]=='J') {
            if (t>0 && str[t-1]=='O') j=0;
            j++;
            o=0;
            i=0;
        } else if (str[t]=='O') {
            o++;
            i=0;
            if (o>j) {
                j=0;
                o=0;
            }
        } else {
            i++;
            j=0;
            if (i>o) {
                o=0;
                i=0;
            }
            if (i==o) ans = max(ans, i);
        }
    }
    printf("%d\n", ans);
    return 0;
}

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

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

  for (int d = 1; d <= N; d*=10){
    f += N/d % 10;
  }

  if (N % f == 0){
    cout << "Yes" << endl;
  }
  else {
    cout << "No" << endl;
  }
}


#include<iostream>
using namespace std;
int main(){
  int a, b, c;
  cin >> a >> b;
  if(a >= 10){
    cout << b << "\n";
  }
  else{
    c = b + 100 * (10 - a);
    cout << c << "\n";
  }
}

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

int main() {
int n;
int r;
int x;
cin >> n;
cin >> r;
x = 100*(10-n)+r;
if (n >= 10) {
  cout << r;
} else {
 cout << x;
}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define REP(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rep(i, n) REP(i, 0, n)
#define rrep(i, n) for (int i = (int)(n-1); i >= 0; i--)
#define sz(x) int(x.size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define INF 2e9
#define LINF 1e18
#define mod 1000000007
template<class T> inline bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; }
typedef long long ll;
typedef pair<int, int> P;

int main() {
    int d,g; cin >> d >> g;
    vector<int> p(d), c(d);
    rep(i,d) cin >> p[i] >> c[i];
    int ans = 1001;
    int cnt = 0;
    int score = 0;
    rep(x,1<<d) { //全解きなら1，無解きなら0
        score = 0;
        cnt = 0;
        rep(i,d) {
            if (x & 1<<i) {
                score += 100*(i+1)*p[i]+c[i];
                cnt += p[i];
            }
        }
        //if (score > g) continue;
        int mx;
        rep(i,d) {
            if (!(x & 1<<(d-1-i))) {
                mx = d-1-i;
                break;
            }
        }
        int num = 0;
        while (score < g && num < p[mx]) {
            score += 100*(mx+1);
            num++;
            cnt++;
        }
        if (score >= g) {
            chmin(ans,cnt);
        }
    }
    cout << ans << endl;
}

#include<bits/stdc++.h>
using namespace std;
int head[600100],cnt,n,m,lim,dis[600100];
struct Node{
	int to,next,val;
}edge[4001000];
void ae(int u,int v,int w){
	edge[cnt].next=head[u],edge[cnt].to=v,edge[cnt].val=w,head[u]=cnt++;
}
map<pair<int,int>,int>mp;
priority_queue<pair<int,int> >q;
bool vis[600100];
int dijkstra(){
	dis[1]=0,q.push(make_pair(0,1));
	while(!q.empty()){
		int x=q.top().second;q.pop();
		if(vis[x])continue;vis[x]=true;
		for(int i=head[x];i!=-1;i=edge[i].next)if(dis[edge[i].to]>dis[x]+edge[i].val)dis[edge[i].to]=dis[x]+edge[i].val,q.push(make_pair(-dis[edge[i].to],edge[i].to));
	}
	return dis[n]==0x3f3f3f3f?-1:dis[n];
}
int hs(int x,int c){
	if(mp.find(make_pair(x,c))!=mp.end())return mp[make_pair(x,c)];
	lim++;
//	printf("(%d,%d)->%d\n",x,c,lim);
	ae(x,lim,1);
	ae(lim,x,0);
	return mp[make_pair(x,c)]=lim;
}
int main(){
	scanf("%d%d",&n,&m),memset(head,-1,sizeof(head)),memset(dis,0x3f3f3f3f,sizeof(dis)),lim=n;
	for(int i=1,u,v,w;i<=m;i++){
		scanf("%d%d%d",&u,&v,&w);
		ae(hs(u,w),hs(v,w),0),ae(hs(v,w),hs(u,w),0);
	}
	printf("%d\n",dijkstra());
	return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define ld long double
#define inf LLONG_MAX>>2
#define MAX 1000000
#define mod 1000000007
#define pb push_back
#define f(i,a,n,x) for ((i)=(a);(i)<(n);(i)+=(x))
#define fd(i,a,n,x) for ((i)=(a);(i)>=(n);(i)-=(x))
#define fi first
#define se second
#define mk make_pair
#define pi pair
#define vt vector
using namespace std;
void read(vt<ll> &a,ll n){ll i,temp;f(i,0,n,1){cin>>temp;a.pb(temp);}}
void dfs(ll k,vt<vt<pi<ll,ll>>> &adj,vt<bool> &visited,vt<ll> &dist){
    ll i;
    visited[k]=true;
    f(i,0,adj[k].size(),1)
        if (!visited[adj[k][i].fi]){
            dist[adj[k][i].fi]=dist[k]+adj[k][i].se;
            dfs(adj[k][i].fi,adj,visited,dist);
        }
}
void solve(){
    ll n,i,a,b,c,q,k;
    cin>>n;
    vt<vt<pi<ll,ll>>> adj(n+1);
    vt<ll> dist(n+1);
    vt<bool> visited(n+1,false);
    f(i,1,n,1){
        cin>>a>>b>>c;
        adj[a].pb(mk(b,c));
        adj[b].pb(mk(a,c));
    }
    cin>>q>>k;
    dist[k]=0;
    dfs(k,adj,visited,dist);
    f(i,0,q,1){
        cin>>a>>b;
        cout<<dist[a]+dist[b]<<endl;
    }
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t=1;
    //cin>>t;
    while(t--)
        solve();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define repo(i,n) for(int i = 1; i < (int)(n); i++)
#define pb push_back
#define mp make_pair
#define np next_permutation
#define lb lower_bound
#define ub upper_bound
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
#define mod 1000000007
#define pi acos(-1.0)
const ll INF = 1LL<<61;
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 gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }
ll jou(ll N, ll P){if(P==0) return 1;
  if(P%2==0){ll t = jou(N, P/2);return t*t % mod;
  }return (N * jou(N, P-1)) % mod;}  //jou(n,mod-2)で逆元
//intの最大値2147483647 ≒ 2×10^9
//long longの最大値9223372036854775807 ≒ 9×10^18
//'大文字'+=32;    で小文字に
//  cout << fixed << setprecision (20);   小数点以下2０桁まで
//実行時間制約2秒では２×10^8回くらいまで計算できる

//—————————————————BFSグラフ————————————————

using Graph = vector<vector<pair<ll,ll>>>;

int main() {
    // 頂点数と辺数
    ll n;
    cin >> n;

    // グラフ入力受取
    Graph G(n);
    rep(i,n-1) {
        ll a,b,c;
        cin >> a >> b >> c;
        auto x=mp(b-1,c);
        G[a-1].pb(x);
        auto y=mp(a-1,c);
        G[b-1].pb(y);
    }

    ll q,k;
    cin>>q>>k;
    k--;

    // BFS のためのデータ構造
    vector<ll> dist(n, 1000000000000000000); // 全頂点を「未訪問」に初期化
    deque<ll> que;

    // 初期条件 (頂点 0 を初期ノードとする)
    dist[k] = 0;
    que.pb(k); // 0 を橙色頂点にする

    // BFS 開始 (キューが空になるまで探索を行う)
    while (!que.empty()) {
        ll v = que.front(); // キューから先頭頂点を取り出す
        que.pop_front();

        // v から辿れる頂点をすべて調べる
        for (auto nv : G[v]) {
            // 新たな白色頂点 nv について距離情報を更新してキューに追加する
            if(dist[nv.fi]>dist[v] + nv.se){
            dist[nv.fi] = dist[v] + nv.se;
            que.pb(nv.fi);
            }
        }
    }

  rep(i,q){
    ll x,y;
    cin>>x>>y;
    cout << dist[x-1]+dist[y-1] << endl;
  }

}


/*#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")*/
#include<bits/stdc++.h>
#define ll long long
#define inf 1000000005
#define put putchar('\n')
#define F(i,a,b) for (int i=(a);i<=(b);i++)
#define D(i,a,b) for (int i=(a);i>=(b);i--)
#define go(i,t) for (int i=head[t];i;i=Next[i])
#define sqr(x) ((x)*(x))
#define re register
#define mp make_pair
#define fi first
#define se second
#define pa pair<int,int>
#define pb push_back
#define be begin()
#define en end()
#define ret return puts("-1"),0;
#define mod 1000000007
#define N 500055
#define int ll
using namespace std;
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
inline int read(){char c=getchar();int tot=1;while ((c<'0'|| c>'9')&&c!='-') c=getchar();if (c=='-'){tot=-1;c=getchar();}
int sum=0;while (c>='0'&&c<='9'){sum=sum*10+c-'0';c=getchar();}return sum*tot;}
inline void wr(int x){if (x<0) {putchar('-');wr(-x);return;}if(x>=10)wr(x/10);putchar(x%10+'0');}
inline void wrn(int x){wr(x);put;}inline void wri(int x){wr(x);putchar(' ');}
inline void wrn(int x,int y){wri(x);wrn(y);}inline void wrn(int a,int b,int c){wri(a);wrn(b,c);}
int n,m,x[N],p[N],l,r,ans,s,tot,z[N];
signed main(){
	n=read();s=read();
	F(i,1,n){
		x[i]=read();p[i]=read();
	}
	l=1;r=n;
	while (x[l]<s&&x[r]>s&&l<r){
		if (p[l]>=p[r]){
			p[l]+=p[r];z[++tot]=r;r--;
		}
		else{
			p[r]+=p[l];z[++tot]=l;l++;
		}
	}
	if (s>x[r]) F(i,l,r) z[++tot]=i;
	else D(i,r,l) z[++tot]=i;
	ans+=abs(s-x[z[tot]]);
	D(i,tot,2) ans+=abs(x[z[i]]-x[z[i-1]]);
	wrn(ans);
	return 0;
}

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

int N, M;
vector<vector<int>> G;
vector<int> indeg;  // 入次数
vector<bool> visited;
vector<int> ans;  // トポロジカルソートの結果

void bfs(int s) {
  queue<int> q;
  q.push(s);
  visited.at(s) = true;
  while (!q.empty()) {
    int cur = q.front();
    q.pop();
    for (int nx : G.at(cur)) {
      indeg.at(nx)--;
      if (indeg.at(nx) == 0 && !visited.at(nx)) {
        q.push(nx);
        ans.at(nx) = cur + 1;
      }
    }
  }
}

int main() {
  cin >> N >> M;
  G.resize(N);
  for (int i = 0; i < N-1+M; i++) {
    int a, b; cin >> a >> b;
    a--; b--;
    G.at(a).push_back(b);
  }

  indeg.resize(N);
  visited.resize(N);
  ans.resize(N);
  for (int i = 0; i < N; i++) {
    for (int e : G.at(i)) {
      indeg.at(e)++;
    }
  }
  for (int i = 0; i < N; i++) {
    if (indeg.at(i) == 0 && !visited.at(i)) bfs(i);
  }
  for (int v : ans) cout << v << endl;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <cassert>
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
#define srep(i,n,m) for(int i=n;i<m;i++)
#define elif else if
#define INF 1000000007
#define pi 3.141592653589793
using namespace std;
int saidaikouyakusuu(int a,int b){
    if(b==0) return a;
    return saidaikouyakusuu(b,a%b);
}
int saisyoukoubaisuu(int a,int b){
    return a*b/saidaikouyakusuu(a,b);
}
int n,m,cnt=0,aa[220000],ans=0,x,y,ab[220000];
pair<int,int> pp[220000];
string s,ss[220000];
char c;
queue<int> que;
signed main(){
    cin>>n>>m>>x>>y;
    rep(i,n){
        cin>>aa[i];
        x=max(x,aa[i]);
    }
    rep(i,m){
        cin>>ab[i];
        y=min(y,ab[i]);
    }
    if(y<=x){
        cout<<"War"<<endl;
    }else{
        cout<<"No War"<<endl;
    }
}

#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
  ll a;
  cin>>a;
  ll b;
  cin>>b;
  ll c=-100;
  ll d=100;
  ll e,f;
  cin>>e>>f;
  for(ll i=0; i<a;i++){
    ll g;
    cin>>g;
    c=max(g,c);
  }
  for(ll i=0;i<b;i++){
    ll h;
    cin>>h;
    d=min(h,d);
  }
  if(c+1>d){
    cout<<"War"<<endl;
    return 0;
  }

    for(ll i=e+1;i<=f;i++){
      if(c+1<=i&&i<=d){
        cout<<"No War"<<endl;
        return 0;
      }
    }
    cout<<"War"<<endl;
  return 0;
}


#include<iostream>
using namespace std;

int main(void) {
    string N; cin >> N;
    bool is7 = false;
    for (int i = 0; i < N.size(); i++) {
        if (N[i] == '7') {
            is7 = true;
        }
    }
    if (is7) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}

#include<stdio.h>

int main(){
	int n;
	scanf("%d", &n);

	int ratusan = 0, puluhan = 0, satuan= 0;

	ratusan = n / 100;
	puluhan = (n / 10) - (ratusan * 10); //misal n = 271, 271 - 2
	satuan = n % 10;

	if(ratusan == 7 || puluhan == 7 || satuan == 7){
		printf("Yes\n");
	}
	else{
		printf("No\n");
	}
	return 0;
}


#include <bits/stdc++.h>
#define enter putchar('\n')
#define space putchar(' ')
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
vector<pii> E[500005];
set<pii> s;
int n, m, ncnt, d[500005], id[500005][2];
struct EDGE {
	int l, r, c;
} e[200005];
template <class T> int read(T &x) {
	x = 0; int f = 1; char c = getchar();
	while (c > -1 && c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); }
	if (c == -1) return 0;
	while (c >= '0' && c <= '9') { x = x * 10 + c - 48; c = getchar(); }
	return x *= f, 1;
}
template <class T> void write(T x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + 48);
}
bool cmp(EDGE a, EDGE b) {
	return a.c < b.c;
}
int main() {
	while (read(n), read(m)) {
		ncnt = n;
		for (int i = 1; i <= n; ++i)
			E[i].clear();
		for (int i = 1; i <= m; ++i)
			read(e[i].l), read(e[i].r), read(e[i].c);
		sort(e + 1, e + m + 1, cmp);
		for (int i = 1; i <= n; ++i)
			id[i][0] = 0;
		for (int i = 1; i <= m; ++i) {
			if (id[e[i].l][0] != e[i].c) {
				id[e[i].l][0] = e[i].c;
				id[e[i].l][1] = ++ncnt;
				E[ncnt].clear();
				E[ncnt].pb(mp(e[i].l, 1));
				E[e[i].l].pb(mp(ncnt, 1));
			}
			if (id[e[i].r][0] != e[i].c) {
				id[e[i].r][0] = e[i].c;
				id[e[i].r][1] = ++ncnt;
				E[ncnt].clear();
				E[ncnt].pb(mp(e[i].r, 1));
				E[e[i].r].pb(mp(ncnt, 1));
			}
			E[id[e[i].l][1]].pb(mp(id[e[i].r][1], 0));
			E[id[e[i].r][1]].pb(mp(id[e[i].l][1], 0));
		}
		fill(d, d + ncnt + 1, -1);
		d[1] = 0;
		s.insert(mp(d[1], 1));
		while (!s.empty()) {
			int u = s.begin() -> se;
			s.erase(s.begin());
			for (int i = 0; i < E[u].size(); ++i) {
				int v = E[u][i].fi;
				if (d[v] > d[u] + E[u][i].se || d[v] == -1) {
					s.erase(mp(d[v], v));
					d[v] = d[u] + E[u][i].se;
					s.insert(mp(d[v], v));
				}
			}
		}
		write(d[n] >> 1), enter;
	}
	return 0;
}

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

int n, m;
int sol[100001];

vector <pair <int, int> > v[100001];
unordered_map <int, int> used[100001];

queue <int> q;

void dfs(int nod, int cul, int val){
    if(nod == n){
        printf("%d", sol[n]);
        exit(0);
    }

    for(auto it : v[nod]){
        if(it.second == cul){
            if(sol[it.first] < val - 1) continue ;
            if(used[it.first].count(cul)) continue ;

            used[it.first][cul] = 1;

            if(sol[it.first] > val){
                sol[it.first] = val;
                q.push(it.first);
            }
            dfs(it.first, cul, val);
        }
    }
}

void dijkstra(){
    memset(sol, 0x3f, sizeof(sol));

    q.push(1);
    sol[1] = 0;

    int ind = 0;
    while(!q.empty()){
        int nod = q.front();
        q.pop();

        for(auto it : v[nod]){
            if(sol[it.first] < sol[nod]) continue ;
            if(used[it.first].count(it.second)) continue ;

            used[it.first][it.second] = 1;
            used[nod][it.second] = 1;
            if(sol[it.first] > sol[nod] + 1){
                sol[it.first] = sol[nod] + 1;
                q.push(it.first);
            }
            dfs(it.first, it.second, sol[nod] + 1);
        }
    }
}

int main()
{
    scanf("%d%d", &n, &m);

    int x, y, c;
    for(int i = 1; i <= m ; ++i){
        scanf("%d%d%d", &x, &y, &c);
        v[x].push_back({y, c});
        v[y].push_back({x, c});
    }

    dijkstra();

    printf("-1");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mod 1000000007
main()
{
    ll n,m,a=0,b=0,temp=0,prev,ans,i;
    scanf("%lld %lld",&n,&m);
    ll len[n],wid[m];
    for(i=0;i<n;i++)
    {
        scanf("%lld",&len[i]);
    }
    sort(len,len+n);
    for(i=0;i<m;i++)
    {
        scanf("%lld",&wid[i]);
    }
    sort(wid,wid+m);

    for(i=1;i<n;i++)
    {
       a=a+(len[i]-len[0]);
       //printf("%lld\n",a);
    }
    temp=a;
    for(i=1;i<n;i++)
    {
      prev=temp;
      temp=prev-(n-i)*(len[i]-len[i-1]);
      a=a%mod+temp%mod;
      //printf("%lld\n",a);
    }

    for(i=1;i<m;i++)
    {
       b=b+(wid[i]-wid[0]);
       //printf("%lld\n",b);
    }
    temp=b;
    for(i=1;i<m;i++)
    {
      prev=temp;
      temp=prev-(m-i)*(wid[i]-wid[i-1]);
      b=b%mod+temp%mod;
      //printf("%lld\n",b);
    }
    ans=((a%mod)*(b%mod))%mod;
    printf("%lld\n",ans);
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<ll,ll> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
#define M 1000000007
#define all(a) (a).begin(),(a).end()
#define rep(i,n) reps(i,0,n)
#define reps(i,m,n) for(int i=(m);i<(n);i++)
int main(){
  ll n,k;cin>>n>>k;
  vector<ll> a(n),b(k);
  rep(i,n)cin>>a[i];
  rep(i,k)cin>>b[i];
  ll c=0LL,d=0LL;
  ll j=-n+1;
  rep(i,n){
    c+=a[i]*j;
    j+=2;
  }
  j=-k+1;
  rep(i,k){
    d+=b[i]*j;
    j+=2;
  }
  cout<<(c%M)*(d%M)%M;
}


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

using namespace std;

typedef long long ll;

struct problem {
	ll l, r;
	problem() = default;
	problem(ll a, ll b) { l = a, r = b; }
};

int N;
problem pr[100000 + 100];

ll a[100000 + 10] = {}, b[100000 + 10] = {};

int main() {
	cin >> N;
	for (int i = 0; i < N; i++)cin >> pr[i].l >> pr[i].r;

	sort(pr, pr + N, [](problem a, problem b) {
		if (a.l != b.l)return a.l < b.l;
		else return a.r > b.r;
	});

	int p = 0, q = 0;//pは再左端のrを持つ区間番号　qは再右端のlを持つ区間番号
	for (int i = 1; i < N; i++) {
		if (pr[p].r > pr[i].r)p = i;
	}
	for (int i = 1; i < N; i++) {
		if (pr[q].l < pr[i].l)q = i;
	}
	ll ans = 0;

	//pとqを1つの集合に入れる
	ans += max(0LL, pr[p].r - pr[q].l + 1);
	ll largest = 0;
	for (int i = 0; i < N; i++) {
		if (i == p || i == q)continue;
		largest = max(largest, pr[i].r - pr[i].l + 1);
	}
	ans += largest;

	//pとqを別々の集合に入れる。a[i] := i個p以外を含んで、その時点での結果
	a[0] = pr[p].r - pr[p].l;
	ll m = pr[p].l;
	for (int i = 1; i <= N; i++) {
		m = max(m, pr[i - 1].l);
		a[i] = max(0LL, pr[p].r - m + 1);
	}

	b[0] = pr[q].r - pr[q].l;
	ll M = pr[q].r;
	for (int i = 1; i <= N; i++) {
		M = min(M, pr[N - i].r);
		b[i] = max(0LL, M - pr[q].l + 1);
	}

	for (int i = 0; i <= N; i++)ans = max(ans, a[i] + b[N - i]);
	cout << ans << endl;

	return 0;
}


#include <bits/stdc++.h>

typedef long long LL;

//container util
//------------------------------------------
#define PB push_back
#define MP make_pair
#define DECIM(digits)  cout<<fixed<<setprecision(digits)
#define SZ(a) int((a).size())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);

//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))

using namespace std;
int main(void)
{
  for(;;){
    int n;
    cin >> n;
    if(!n) return 0;
    vector<pair<int,int> >gem;
    gem.resize(n);
    REP(i,n){
      int x,y;
      cin >> x >> y;
      gem[i]=MP(x,y);
    }
    int m;
    cin >> m;
    pair<int,int> pos=MP(10,10);
    REP(i,m){
      string news;
      int amount;
      cin >> news >> amount;
      while(amount--){
	if(news=="N")
	  pos.second++;
	if(news=="E")
	  pos.first++;
	if(news=="W")
	  pos.first--;
	if(news=="S")
	  pos.second--;
	for(auto j=gem.begin();j!=gem.end();)
	  if(pos==*j) j=gem.erase(j);
	  else ++j;
      }
    }
    if(gem.empty()) cout << "Yes" << endl;
    else cout << "No" << endl;
  }
}

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

int main() {
	string str, order, p;
	int q, n1, n2;
	cin >> str >> q;
	for (int i = 0;i < q;i++) {
		cin >> order >> n1 >> n2;
		if (order == "print")
			cout << str.substr(n1, n2-n1+1) << endl;
		else if (order == "reverse") {
			reverse(str.begin()+n1,str.begin()+n2+1);
		}
		else {
			cin >> p;
			str.replace(n1, n2-n1+1, p);
		}

	}

}


#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
struct point{int x;int y;};
int i,j,k,count1=0,count2=0;

int main(){
    int a,b,c;
    cin>>a>>b>>c;
    if(c>min(a,b)&&c<max(a,b))cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
}

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

int n, h, w;

int main() {
	scanf("%d %d %d", &n, &h, &w);
	printf("%d\n", (n - h + 1) * (n - w + 1));
	return 0;
}


#include <bits/stdc++.h>
#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++)
#define pi 3.14159265359
#define all(i) i.begin(),i.end()
using namespace std;
const long long INF=1e9+7;
const string alp="abcdefghijklmnopqrstuvwxyz"; //26
const string ALP="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef pair<ll,ll> P;
typedef tuple<ll,ll,ll> T;
//const ll MOD=998244353LL;
//const ll MOD=1777777777LL;

int main() {
  string s;
  cin>>s;
  ll count=0;
  bool judge=false;
  for(int i=2;i<s.size()-1;i++){
    if(s[i]=='C'){
      count++;
    }
  }
  if(count==1) judge=true;
  if(s[0]!='A'){
    judge=false;
  }
  for(int i=0;i<s.size();i++){
    for(int j=0;j<26;j++){
      if(s[i]!='A'&&s[i]!='C'&&s[i]==ALP[j]){
        judge=false;
      }
    }
  }
  if(judge) cout<<"AC"<<endl;
  else cout<<"WA"<<endl;
}

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

int main() {
  int N;
  cin >> N;
  int M = N;
  int i = 0;
  int sum = 0;

  while (M >= 1) {
    sum += (M - (M / 10) * 10);
    M = M / 10;
  }

  if (N % sum == 0) {
    cout << "Yes" << endl;
  }
  else {
    cout << "No" << endl;
  }
}


#include<iostream>
#include<math.h>
using namespace std;
int isPrime(int n){
    if(n<2)return 0;
    double sqrtn= sqrt(n);
    for(int i=2;i<=sqrtn;i++){
        if(n%i==0)return 0;
    }
    return 1;
}
int main(void){
    int n=1;
    while(n){
        cin>>n;
        for(int i=n;i>0;i--){
            if(isPrime(i)*isPrime(i-2)){
                cout<<i-2<<" "<<i<<endl;
                break;
            }
        }
    }
    return 0;
}

#include<bits/stdc++.h>
#define ll long long int
#define endl '\n'
#define M 1000000007
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define f first
#define s second
#define b begin
#define e end
#define pb push_back
#define mp make_pair
#define FOR(i,a,b) for(i=a;i<b;i++)
#define RFOR(i,a,b) for(i=a;i>=b;i--)
#define all(x) x.begin(),x.end()
#define itfr(it,x) for(it=x.begin();it!=x.end();it++)
#define flash ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;

int main()
{
    flash;
    //sieve();
    ll T=1,t,n,m,q,k,i,j;
    // cin>>T;
    while(T--)
    {
      string st;
      cin>>st;
      int fl=1;
      n = st.size();
      vector<int> ind(26,-10);
      FOR(i,0,n)
      {
        int x = ind[st[i]-'a'];
        if((i-x)<3){
          cout<<x+1<<" "<<i+1<<endl;
          fl=0;
          break;
        }
        ind[st[i]-'a']=i;
      }
      if(fl)
        cout<<-1<<" "<<-1<<endl;
    }
}


#include "bits/stdc++.h"

using namespace std;

void Main() {
    long long N;
    cin >> N;
    map<long long, set<pair<long long, long long> > > tree;
    for (long long i = 0; i < N - 1; ++i) {
        long long a, b, c;
        cin >> a >> b >> c;
        if (tree.count(a) == 0) {
            tree.insert(make_pair(a, set<pair<long long, long long> >()));
        }
        tree[a].insert(make_pair(b, c));
        if (tree.count(b) == 0) {
            tree.insert(make_pair(b, set<pair<long long, long long> >()));
        }
        tree[b].insert(make_pair(a, c));
    }

    long long Q, K;
    cin >> Q >> K;
    vector<long long> distanceFromK(N + 1, -1LL);
    distanceFromK[K] = 0LL;
    queue<long long> q;
    q.push(K);
    while (!q.empty()) {
        long long f = q.front();
        q.pop();
        long long distanceFromTop = distanceFromK[f];
        const set<pair<long long, long long> >& nextNodes = tree[f];
        for (auto e : nextNodes) {
            if (distanceFromK[e.first] < 0) {
                q.push(e.first);
                distanceFromK[e.first] = e.second + distanceFromTop;
            }
        }
    }

    for (long long i = 0; i < Q; ++i) {
        long long x, y;
        cin >> x >> y;
        long long dx = distanceFromK[x];
        long long dy = distanceFromK[y];
        cout << (dx + dy) << endl;
    }

}

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

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

const ll INF = 1LL << 60;

ll N, Q;
vector<tuple<ll, ll, ll>> v;
set<P> st;

int main() {
    cin >> N >> Q;
    v.resize(N);

    rep(i, N) {
        ll s, t, x;
        cin >> s >> t >> x;
        v[i] = make_tuple(x, s, t);
    }
    sort(v.begin(), v.end());

    rep(i, Q) {
        ll d; cin >> d;
        st.insert(P(d, i));
    }

    vector<ll> ans(Q);

    rep(i, N) {
        ll x, l, r;
        tie(x, l, r) = v[i];

        auto iter = st.lower_bound(P(l - x, -1));
        while (iter != st.end()) {
            if (iter->first >= r - x) break;
            ans[iter->second] = x;
            st.erase(iter++);
        }
    }

    rep(i, Q) {
        if (ans[i] == 0) {
            cout << -1 << endl;
        } else {
            cout << ans[i] << endl;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

template<typename T, typename ...Ts>
vector<T> fusion(vector<T> bs,Ts... ts){
  auto append=[&](auto vs){for(auto v:vs) bs.emplace_back(v);};
  initializer_list<int>{(void(append(ts)),0)...};
  return bs;
}

// longest common prefix of s and s[i:n]
vector<int> zalgorithm(vector<int> s){
  int n=s.size();
  vector<int> as(n,0);
  as[0]=n;
  int i=1,j=0;
  while(i<n){
    while(i+j<n&&s[j]==s[i+j]) j++;
    as[i]=j;
    if(j==0){
      i++;
      continue;
    }
    int k=1;
    while(i+k<n&&k+as[k]<j) as[i+k]=as[k],k++;
    i+=k;
    j-=k;
  }
  return as;
}

//INSERT ABOVE HERE
signed main(){
  int n;
  cin>>n;
  vector<int> as(n),bs(n);
  for(int i=0;i<n;i++) cin>>as[i];
  for(int i=0;i<n;i++) cin>>bs[i];

  vector<int> cs(n),ds(n);
  for(int i=0;i<n;i++){
    cs[i]=as[i]^as[(i+1)%n];
    ds[i]=bs[i]^bs[(i+1)%n];
  }

  vector<int> ss=fusion(ds,cs,cs);
  auto zs=zalgorithm(ss);
  for(int i=0;i<n;i++)
    if(zs[n+i]>=n) cout<<i<<" "<<(as[i]^bs[0])<<endl;

  return 0;
}

#include <stdio.h>
#include <algorithm>

using namespace std;

int main(){
    int n,max_num = -1000001,min_num = 1000001,tmp;
    long long int sum = 0;
    scanf("%d",&n);
    for(int i = 0; i < n; i++){
        scanf("%d",&tmp);
        sum += tmp;
        max_num = max(max_num,tmp);
        min_num = min(min_num,tmp);
    }
    printf("%d %d %lld\n",min_num,max_num,sum);
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <functional>
#include <cmath>
#include <set>
#include <queue>
#include <vector>
#include <climits>
#include <sstream>
#include <iomanip>
#include <map>
#include <stack>
using namespace std;

int main()
{
	int n, m;
	cin >> n >> m;
	vector<long long> x(n);
	vector<long long> y(m);
	for (auto i = 0; i < n; ++i)
	{
		cin >> x[i];
	}
	for (auto i = 0; i < m; ++i)
	{
		cin >> y[i];
	}

	auto sumX = 0ll;
	auto mod = (long long)1e9 + 7;
	for (auto i = 1; i < n; ++i)
	{
		auto diff = x[i] - x[i - 1];
		sumX += (((diff * i) % mod) * (n - 1 - i + 1)) % mod;
		sumX %= mod;
	}

	auto sum = 0ll;
	for (auto i = 1; i < m; ++i)
	{
		auto diff = y[i] - y[i - 1];
		sum += (((((diff * i) % mod) * (m - 1 - i + 1)) % mod) * sumX) % mod;
		sum %= mod;
	}

	cout << sum << endl;

	return 0;
}

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <cassert>

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

using namespace std;
typedef long long int ll;
const int INF = 1000000000;
const double PI = acos(-1);
const ll mod = 1000000007;

int main()
{
    int n;
    string s;
    cin >> n >> s;

    vector<int> c(n);
    vector<int> r_num(n + 1, 0);
    vector<int> g_num(n + 1, 0);
    vector<int> b_num(n + 1, 0);
    rep(i, n) {
        r_num[i + 1] = r_num[i];
        g_num[i + 1] = g_num[i];
        b_num[i + 1] = b_num[i];
        if (s[i] == 'R') {
            c[i] = 0;
            r_num[i + 1] = r_num[i] + 1;
        }
        else if (s[i] == 'G') {
            c[i] = 1;
            g_num[i + 1] = g_num[i] + 1;
        }
        else {
            c[i] = 2;
            b_num[i + 1] = b_num[i] + 1;
        }
    }

    ll ans = 0;
    for (int i = 0; i < n-2; i++) {
        for (int j = i + 1; j < n-1; j++) {
            if (c[i] == c[j]) continue;
            if (c[i] + c[j] == 1) {  // RGのとき
                ans += b_num[n] - b_num[j + 1];
                if (2*j - i < n) {
                    if (c[2 * j - i] == 2) ans -= 1;
                }
            }
            else if (c[i] + c[j] == 3) {  // GBのとき
                ans += r_num[n] - r_num[j + 1];
                if (2 * j - i < n) {
                    if (c[2 * j - i] == 0) ans -= 1;
                }
            }
            else {  // RBのとき
                ans += g_num[n] - g_num[j + 1];
                if (2 * j - i < n) {
                    if (c[2 * j - i] == 1) ans -= 1;
                }
            }
        }
    }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vc = vector<char>;
using vvc = vector<vc>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
const ll INF = 1LL << 60;
const ll MOD = 1e9 + 7;
#define rep(i, n) for (ll i = 0; i < (n); i++)
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#ifndef ONLINE_JUDGE
    #define debug(x) cerr << #x << ": " << x << endl;
#else
    #define debug(x)
#endif

ll dp[1<<20], cost[1<<20];

int main() {
    cin.tie(0);ios::sync_with_stdio(false);cout << fixed << setprecision(20);

    ll N; cin >> N;
    vvll a(N, vll(N));
    rep(i, N) rep(j, N) cin >> a[i][j];

    rep(s, 1ll<<N) {
        rep(i, N) rep(j, N) {
            if(i >= j) continue;
            if(s>>i&1 && s>>j&1) cost[s] += a[i][j];
        }
    }

    rep(s, 1ll<<N) {
        for(ll t = s; t > 0; t = (t-1)&s) {
            chmax(dp[s], dp[s-t] + cost[t]);
        }
    }
    cout << dp[(1<<N)-1] << endl;
}

#include<bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define PI acos(-1)
#define pcnt __builtin_popcountll
#define rng(a) a.begin(), a.end()
#define sz(x) (int)(x).size()
#define v(T) vector<T>
#define vv(T) v(v(T))

using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;

template<typename T>inline istream& operator>>(istream&i,v(T)&v)
{rep(j,sz(v))i>>v[j];return i;}
template<typename T1,typename T2>inline istream& operator>>(istream&i,pair<T1,T2>&v)
{return i>>v.fi>>v.se;}
template<class T> inline bool chmax(T& a, T b) {if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) {if (a > b) { a = b; return true; } return false; }

ll INF = 1001001001;
ll LINF = 1001001001001001001ll;

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

    ll N, M, v, p;
    cin>>N>>M>>v>>p;
    vl as(N);
    cin>>as;
    sort(rng(as));
    reverse(rng(as));

    ll mi = N;
    rep(i, N) if (as[i] + M < as[p - 1]) {
        mi = i;
        break;
    }
    ll l = p - 1;
    ll r = mi;
    while (l + 1 < r) {
        ll m = (l + r) / 2;
        ll s = 0;
        s += M * (p - 1 + N - m);
        for (int i = p - 1; i < m; ++i) {
            s += as[m] + M - as[i];
        }
        if (s >= M * v) l = m;
        else r = m;
    }
    cout<<l + 1<<endl;
}


#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
int V,E,r;
const int Inf = 10000*100000+100;
ll C[100010];
int main(){
	while(cin >> V >> E >> r && V >0){
		vector< vector< P > > v(V+10);
		for(int i=0;i<E;i++){
			ll s,t,d;
			cin >> s >> t >> d;
			v[s].push_back(make_pair(d,t));
		}
		priority_queue<P> Q;
		Q.push(P(0,r));
		for(int i=0;i<V;i++){
			C[i] = Inf;
		}
		C[r] = 0;
		while(!Q.empty()){
			P t = Q.top();
			ll s = t.second;
			Q.pop();
			if(C[s] < t.first) continue;
			for(int i=0;i<v[s].size();i++){
				P e = v[s][i];
				if(C[e.second] > C[s] + e.first){
					C[e.second] = C[s] + e.first;
					Q.push(make_pair(-C[e.second],e.second));
				}
			}
		}
		for(int i=0;i<V;i++){
			if(C[i] < Inf) cout << C[i] << endl;
			else cout << "INF" << endl;
		}
	}
}
#if 0
所要時間45分程度。ほとんどの部分はテキストを見ながら自力で書いたがうまくいかず，
蟻本(プログラミングコンテストチャレンジブック)(最近友人から譲ってもらった)を見て28行目を追加しAC
「確定しているので無視」ということの意味があまりわかっていなかったらしい。
#endif

#include <iostream>
#include <iomanip>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <utility>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <numeric>

using namespace std;

typedef uint64_t u64;
typedef int64_t s64;
typedef uint32_t u32;
typedef int32_t s32;
typedef vector<s32> vs32;
typedef vector<u32> vu32;
typedef vector<s64> vs64;
typedef vector<u64> vu64;

const double PI=3.14159265358979323846;

#define MAX(x, y) ((x) < (y) ? (y) : (x))
#define MIN(x, y) ((x) > (y) ? (y) : (x))

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

#define CEIL(x, y) (((x) + (y) - 1) / (y))
#define MOD 1000000007ULL

#define IN(l, r, x) ((l) <= (x) && (x) < (r))

using P = pair<int, int>;

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

    int n, q;
    cin >> n >> q;

    vector< pair<int, P> > st;
    rep (i, n)
    {
        int s, t, x;
        cin >> s >> t >> x;
        st.emplace_back(s - x, P{1, x});
        st.emplace_back(t - x, P{-1, x});
    }
    sort(st.begin(), st.end());

    multiset<int> ms;
    int idx = 0;
    rep (i, q)
    {
        int d;
        cin >> d;
        while (idx < st.size() && d >= st[idx].first)
        {
            if (st[idx].second.first == 1)
            {
                ms.insert(st[idx].second.second);
            }
            else
            {
                ms.erase(ms.find(st[idx].second.second));
            }
            ++idx;
        }

        if (ms.empty()) cout << "-1\n";
        else cout << *ms.begin() << "\n";
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rep2(i, s, n) for (ll i = (s); i < (ll)(n); i++)
#define all(v) v.begin(), v.end()
#define sz(v) v.size()
#define INF 100000000000000 //10^14
template <typename T>
bool chmax(T &a, const T& b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool chmin(T &a, const T& b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}

// Sieve of Eratosthenes
// https://youtu.be/UTVg7wzMWQc?t=2774
struct Sieve {
  using P = pair<int, int>;
  int n;
  vector<int> f, primes; //f.at(x)はxの最小素因数
  Sieve(int n=1):n(n), f(n+1) {
  f[0] = f[1] = -1;
  for (ll i = 2; i <= n; ++i) {
    if (f[i]) continue; //ここでf[i]==0なら素数
    primes.push_back(i);
    f[i] = i;
    for (ll j = i*i; j <= n; j += i) {
  if (!f[j]) f[j] = i;
    }
  }
  }
  bool isPrime(int x) { return f[x] == x;}
  vector<int> factorList(int x) { //xの素因数を小さい順に列挙
  vector<int> res;
  while (x != 1) {
    res.push_back(f[x]);
    x /= f[x];
  }
  return res;
  }
  vector<P> factor(int x) {
  vector<int> fl = factorList(x);
  if (fl.size() == 0) return {};
  vector<P> res(1, P(fl[0], 0));
  for (int p : fl) { //ここでランレングス圧縮
    if (res.back().first == p) {
  res.back().second++;
    } else {
  res.emplace_back(p, 1);
    }
  }
  return res;
  }
};
// Sieve sieve(N);でN以下の各自然数の最小素因数を調べ上げる
// sieve.factor(M)でMの素因数分解

vector<pair<long long, long long> > prime_factorize(long long N) {
  vector<pair<long long, long long> > res;
  for (long long a = 2; a * a <= N; ++a) {
    if (N % a != 0) continue;
    long long ex = 0; // 指数
    // 割れる限り割り続ける
    while (N % a == 0) {
     ++ex;
      N /= a;
    }
    // その結果を push
    res.push_back({a, ex});
  }
  // 最後に残った数について
  if (N != 1) res.push_back({N, 1});
  return res;
}

int main()
{
    ll N;
    cin >> N;
    Sieve sieve(277775);
    vector<ll> a(N);
    a.at(0) = 2;
    a.at(1) = 3;
    rep2(i, 2, N){
        int p = a.at(i-1) + 10;
        while(true){
            if(sieve.f.at(p) == p){
                a.at(i) = p;
                break;
            }
            p += 10;
        }
    }
    rep(i, N-1){
        cout << a.at(i) << " ";
    }
    cout << a.at(N-1) << endl;
}

#include<iostream>
#include<string>

using namespace std;

int conv(char str)
{
	if(str=='I')
	{
		return 1;
	}
	else if(str=='V')
	{
		return 5;
	}
	else if(str=='X')
	{
		return 10;
	}
	else if(str=='L')
	{
		return 50;
	}
	else if(str=='C')
	{
		return 100;
	}
	else if(str=='D')
	{
		return 500;
	}
	else if(str=='M')
	{
		return 1000;
	}
}

int conv(string str)
{
	int ans=0;
	for(int i=0;i<str.length();i++)
	{
		if(i==str.length()-1)
		{
			ans+=conv(str[i]);
		}
		else if(conv(str[i])<conv(str[i+1]))
		{
			ans-=conv(str[i]);
		}
		else ans+=conv(str[i]);
	}
	return ans;
}

int main(void)
{
	string str;
	while(cin>>str)
	{
		cout<<conv(str)<<endl;
	}
}


#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define pi 3.141592653589793238
#define int long long
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

int dp[2][100005];
const int mod=1e9+7;

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

#ifndef ONLINE_JUDGE
    if(fopen("INPUT.txt","r"))
    {
    freopen ("INPUT.txt" , "r" , stdin);
    freopen ("OUTPUT.txt" , "w" , stdout);
    }
#endif

    int n,x;
    cin>>n>>x;
    int a[n+1];
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a+1,a+n+1,greater<int>());

    dp[0][x]=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=0;j<=x;j++)
            dp[i&1][j]=0;
        for(int j=0;j<=x;j++)
        {
            dp[i&1][j%a[i]]+=dp[(i+1)&1][j];
            dp[i&1][j]+=(dp[(i+1)&1][j]*(n-i))%mod;
            dp[i&1][j]%=mod;
            dp[i&1][j%a[i]]%=mod;
        }
    }

    int ans=0;
    for(int i=0;i<=x;i++)
    {
        ans=(ans+dp[n&1][i]*i)%mod;
    }
    cout<<ans;

}

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

#define DEBUG 0

#if DEBUG
  #define DLOG(...) fprintf(stderr, __VA_ARGS__)
#else
  #define DLOG(...)
#endif

void debug(auto f) {
#if DEBUG
  f();
#endif
}

ll mPrime = int(1e9) + 7;
ll bN, bX;
vector<ll> bS;
vector<ll> facts;
vector<ll> invFacts;
vector<int> tbl;
vector<int> low;  // low[y] == #{ i | s[i] <= y }

ll mAdd(ll x, ll y) {
  ll z = x + y;
  if (z < mPrime)  return z;
  else             return (z - mPrime);
}

ll mSub(ll x, ll y) {
  ll z = x - y;
  if (z >= 0)  return z;
  else         return (z + mPrime);
}

ll mMul(ll x, ll y) {
  return (x * y) % mPrime;
}

ll eGCD(ll a, ll b, ll& s, ll& t) {
  if (a == 0) {
    s = 0;
    t = 1;
    return b;
  }
  ll u;
  ll g = eGCD(b % a, a, t, u);
  s = u - (b / a) * t;
  return g;
}

ll mInv(ll x) {
  ll s, t;
  eGCD(x, mPrime, s, t);
  return s < 0 ? s + mPrime : s;
}

ll tight(ll);

ll loose(ll y, ll len) {
  ll result = mMul(tight(y), mMul(facts.at(len), invFacts.at(low.at(y))));
  DLOG("loose(%lld, %lld) = %lld\n", y, len, result);
  return result;
}

ll tight(ll y) {
  if (tbl.at(y) >= 0)  return tbl.at(y);
  ll len = low.at(y);
  if (len == 0)  return y;
  ll result = 0;
  for (ll i = 0; i < len; i++) {
    ll z = y % bS.at(i);
    result = mAdd(result, loose(z, len-1));
  }
  tbl.at(y) = result;
  DLOG("tight(%lld) = %lld\n", y, result);
  return result;
}

int main() {
  cin >> bN >> bX;
  bS.resize(bN);
  for (ll i = 0; i < bN; i++) {
    cin >> bS.at(i);
  }
  facts.resize(bN+1);
  invFacts.resize(bN+1);
  facts.at(0) = invFacts.at(0) = 1;
  for (ll i = 1; i <= bN; i++) {
    facts.at(i) = mMul(i, facts.at(i-1));
    invFacts.at(i) = mInv(facts.at(i));
  }
  sort(bS.begin(), bS.end());

  low.resize(bX+1);
  ll idx = 0;
  for (ll i = 0; i < bX+1; i++) {
    if (idx < (ll) bS.size() && bS.at(idx) == i)  idx++;
    low.at(i) = idx;
  }

  tbl.resize(bX+1, -1);
  ll ans = loose(bX, bS.size());
  cout << ans << endl;

  return 0;
}


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

int main(){
        int n,m,i,p,cnt_p=0,cnt_a=0;
        string s;
        cin >> n >> m;
        vector<int> pen(n);
        vector<bool> done(n);
        for(i=0;i<m;++i){
                cin >> p >> s;
                --p;
                if(done.at(p)) continue;
                if(s=="WA") ++pen.at(p);
                else{
                        cnt_p += pen.at(p);
                        ++cnt_a;
                        done.at(p) = true;
                }
        }
        cout << cnt_a << " " << cnt_p << endl;
        return 0;
}

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

#define vt          vector
#define sz(x)       int((x).size())
#define all(x)      (x).begin(), (x).end()
#define rall(x)     (x).rbegin(), (x).rend()
#define fi          first
#define se          second

using ll = long long;
using pii = pair<int, int>;

void solve() {
    int n, m;
    cin >> n >> m;
    vt<int> p(n + 1), ac(n + 1);
    while (m--) {
        int x;
        string s;
        cin >> x >> s;
        if (s == "AC") ac[x] = 1;
        else if (!ac[x]) p[x]++;
    }

    int pen = 0;
    for (int i = 1; i <= n; i++) pen += p[i] * ac[i];
    cout << accumulate(all(ac), 0) << ' ' << pen;
}

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

    int tcs = 1;
    for (int tc = 1; tc <= tcs; tc++) {
        // cout << "Case " << tc << ": ";
        solve();
    }
}


#include<iostream>
#include<iomanip>
#include<cassert>
#include<stdexcept>
#include<utility>
#include<functional>
#include<numeric>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<array>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<complex>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<string>
#include<bitset>
#include<memory>
using namespace std;
using ll=long long;

const int SIZE=18;

const ll MOD=1e9+7;

void add(ll &lhs,ll rhs){
    lhs=(lhs+rhs)%MOD;
}
int main(){
    int n;
    cin>>n;
    int xyz[3];
    for(int i=0;i<3;i++) cin>>xyz[i];

    vector<vector<ll>> dp(n+1,vector<ll>(1<<SIZE));
    dp[0][(1<<SIZE)-1]=1;

    vector<int> isAccept(1<<SIZE);

    for(int bit=0;bit<(1<<SIZE);bit++){
        int st=0;
        int buf=0;
        for(int i=0;i<SIZE;i++){
            buf++;
            if(!((bit>>i)&1) && xyz[st]==buf){
                st++;
                buf=0;
                if(st==3){
                    isAccept[bit]=true;
                    break;
                }
            }
        }
    }

    vector<ll> pow10(n);
    pow10[0]=1;
    for(int i=0;i+1<n;i++) pow10[i+1]=pow10[i]*10%MOD;

    ll res=0;
    int mask=(1<<SIZE)-1;
    for(int i=0;i<n;i++){
        for(int bit=0;bit<(1<<SIZE);bit++){
            for(int v=1;v<=10;v++){
                int nex=(bit<<v)+(1<<(v-1))-1;
                nex&=mask;
                add(dp[i+1][nex],dp[i][bit]);
            }
        }
        for(int bit=0;bit<(1<<SIZE);bit++){
            if(isAccept[bit]){
                ll r=pow10[n-1-i];
                res+=r*dp[i+1][bit];
                res%=MOD;
                dp[i+1][bit]=0;
            }
        }
    }

    cout<<res<<endl;

    return 0;
}

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int Mod = 1e9 + 7;
int N, M, X, Y, Z, f[41][1 << 18];
int OK, ALL;
void pls(int &x, int y) { x += y; if (x >= Mod) x -= Mod; }
int main () {
	cin >> N >> X >> Y >> Z;
	M = X + Y + Z;
	OK = (1 << (X + Y + Z - 1)) | (1 << (Y + Z - 1)) | (1 << (Z - 1));
	ALL = (1 << M) - 1;
	f[0][0] = 1;
	for (int i = 1; i <= N; i++) {
		for (int s = 0; s < 1 << M; s++) {
			for (int j = 1; j < 11; j++) {
				int t = ((s << j) | (1 << (j - 1))) & ALL;
				if ((t & OK) == OK) continue;
				pls(f[i][t], f[i - 1][s]);
			}
		}
	}
	int ans = 1;
	for (int i = 1; i <= N; i++) ans = 10ll * ans % Mod;
	for (int i = 0; i < 1 << M; i++) ans = (ans - f[N][i] + Mod) % Mod;
	printf("%d\n", ans);
    return 0;
}


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

typedef long long int ll;
#define INF 1999999999
#define MODA 1000000007
#define PI 3.1415926535897932384626433

int main()
{
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    int a, b, c;
    cin >> a >> b >> c;
    if((c < a && b < c) || (a < c && c < b)){
        cout << "Yes" << endl;
    }
    else{
        cout << "No" << endl;
    }

    return 0;
}

#include<iostream>
using namespace std;

int main(){
  int a,b,c;
  cin >> a >> b >> c;
  cout << ((a-c)*(b-c)<0?"Yes":"No") << endl;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;

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

  int n, q;
  string s;
  cin >> n >> s >> q;

  while (q--) {
    int k;
    cin >> k;

    ll ans = 0, a = 0, b = 0, m = 0;
    for (int i = 0; i < k; i++) {
      if (s[i] == 'D') a++;
      else if (s[i] == 'M') {
        m++;
        b += a;
      } else if (s[i] == 'C') ans += b;
    }

    for (int i = 1; i <= n - k; i++) {
      if (s[i - 1] == 'D') {
        a--;
        b -= m;
      } else if (s[i - 1] == 'M') m--;

      if (s[i + k - 1] == 'D') a++;
      else if (s[i + k - 1] == 'M') {
        m++;
        b += a;
      } else if (s[i + k - 1] == 'C') ans += b;
    }

    cout << ans << '\n';
  }
}

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

class Baseball {
private:
	int out;
	int runner;
	int score;

public:
	//constructor
	Baseball() {
		out = 0;
		runner = 0;
		score = 0;
	}

	//getter
	int getOut() { return out; }
	int getRunner() { return runner; }
	int getScore() { return score; }
	//input OUT
	void execOut() { ++out; }
	//input HIT
	void execHit() {
		if(runner == 3)++score;
		else ++runner;
	}
	//input HOMERUN
	void execHomerun() {
		score += runner + 1;
		runner = 0;
	}

};

int main(){
	int dataSetNum;
	std::cin >> dataSetNum;

	std::vector< Baseball > baseball;
	baseball.resize(dataSetNum);

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

		while(baseball[i].getOut() != 3){
			//input
			std::string tmp;
			std::cin >> tmp;

			if(tmp == "OUT")baseball[i].execOut();
			else if(tmp == "HIT")baseball[i].execHit();
			else if(tmp == "HOMERUN")baseball[i].execHomerun();
		}

	}
	//output
	std::for_each(baseball.begin(), baseball.end(),
    [](Baseball x) { std::cout << x.getScore() << std::endl; } );

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(ll i = 0, i##_len = (n); i < i##_len; ++i)
#define rep2(i, x, n) for(ll i = x, i##_len = (n); i < i##_len; ++i)
#define all(n) begin(n), end(n)
using ll = long long;
using P = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vs = vector<string>;
using vc = vector<char>;
using vb = vector<bool>;
using vd = vector<double>;
vi dir = {-1, 0, 1, 0, -1, -1, 1, 1, -1};

int main() {
  string st;
  cin >> st;
  ll t = 0, s = 0;
  rep(i, st.size()) {
    if(st[i] == 'T') {
      if(s > 0)
        s--;
      else
        t++;
    } else {
      s++;
    }
  }
  cout << t + s << endl;
}

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

int main() {
	string x; cin >> x;
	int n = x.size();
	vector<char> st;
	REP(i, n) {
		if (x[i] == 'S')
			st.push_back('S');
		else {
			if (st.empty())
				st.push_back('T');
			else if (st.back() == 'S')
				st.pop_back();
			else if (st.back() == 'T')
				st.push_back('T');
		}
	}
	cout << st.size() << '\n';
	return 0;
}


#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <string.h>

using namespace std;
static const int INF = 1e9;
static const int SIZE = 10001;
typedef pair<int, int> P;
struct edge
{
	int to;
	int cost;
};

bool isUsed[SIZE];
vector<edge> G[SIZE];

void solve()
{
	int V, E;
	cin >> V >> E;
	for (int i = 0; i < E; ++i)
	{
		int from, to, cost;
		cin >> from >> to >> cost;
		edge e1, e2;
		e1.to = to;
		e1.cost = cost;
		e2.to = from;
		e2.cost = cost;
		G[from].push_back(e1);
		G[to].push_back(e2);
	}
	memset(isUsed, 0, sizeof(isUsed));
	int ans = 0;
	priority_queue<P, vector<P>, greater<P> > pque;
	pque.push(P(0, 0));
	while (!pque.empty())
	{
		P p = pque.top();
		pque.pop();
		int v = p.second;
		if (isUsed[v])
		{
			continue;
		}
		isUsed[v] = true;
		ans += p.first;
		for (int i = 0; i < G[v].size(); ++i)
		{
			edge e = G[v][i];
			pque.push(P(e.cost, e.to));
		}
	}
	cout << ans << endl;
}

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

#include <bits/stdc++.h>

using namespace std;

#define fi first
#define se second

typedef pair<int,int> ii;
typedef pair<int,ii> iii;

class UnionFindDS{
private:
	vector<int> p, h, sz;	// parent, height (rank), size
	int num;
public:
	UnionFindDS(int N){
		p.assign(N,0); for (int i=0; i<N; i++) p[i] = i;
		h.assign(N,0); sz.assign(N,1);
		num = N;
	}
	int numSets(){ return num; }
	int findSet(int i){ return p[i] == i ? i : p[i] = findSet(p[i]); }
	int sizeSet(int i){ return sz[findSet(i)]; }
	bool isSameSet(int i, int j){ return findSet(i) == findSet(j); }
	void unionSet(int i, int j){
		int x = findSet(i), y = findSet(j);
		if (x == y) return;

		num--;
		if (h[x] > h[y]){ p[y] = x; sz[x] += sz[y]; }
		else			{ p[x] = y; sz[y] += sz[x]; h[y] += (h[y] == h[x]); }
	}
};

priority_queue< iii,vector<iii>,greater<iii> > pq;

int main(){

	ios_base::sync_with_stdio(0);

	int V, E;
	cin >> V >> E;

	int u, v, w;
	for (int i=0; i<E; i++){
		cin >> u >> v >> w;

		pq.push(iii(w,ii(u,v)));
	}

	UnionFindDS uf(V);

	int sum = 0;
	while (uf.numSets() > 1 && !pq.empty()){
		iii front = pq.top(); pq.pop();

		u = front.se.fi; v = front.se.se; w = front.fi;

		if (uf.isSameSet(u,v)) continue;

		uf.unionSet(u,v); sum += w;
	}

	if (uf.numSets() > 1) cout << -1  << endl;		// impossible to form spanning tree
	else 				  cout << sum << endl;

	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<numeric>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<list>
#include<bitset>
#include<sstream>
using namespace std;

int main() {

	string S;
	cin >> S;

	string alp = "abcdefghijklmnopqrstuvwxyz";

	if (S.length() < 26) {
		for (int i = 0; i < alp.length(); i++) {
			if (S.find(alp.substr(i, 1)) == string::npos) {
				S += alp.substr(i, 1);
				break;
			}
		}
		cout << S << endl;
	}
	else {
		reverse(S.begin(), S.end());

		if (S == alp) {
			cout << -1 << endl;
		}
		else {
			size_t ii = 0;
			size_t pos = alp.find(S.substr(ii, 1), 0);

			while (pos != string::npos) {
				ii += 1;
				pos = alp.find(S.substr(ii, 1), pos);
			}

			string str = S.substr(ii, 1);

			for (size_t i = 0; i < ii; i++) {
				if (S.substr(i, 1) > str) {
					str = S.substr(i, 1);
					break;
				}
			}

			string ans = str + S.substr(ii + 1);

			reverse(ans.begin(), ans.end());

			cout << ans << endl;
		}
	}

	return 0;
}

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <math.h>
using namespace std;

typedef long long ll;
const int MAXN = 3e5 + 10;
const int Mod = 1e9 + 7;
int N;
char S[MAXN];
int To[8][2] = {{3, 1}, {5, 2}, {2, 2}, {4, 7}, {3, 3}, {6, 1}, {5, 5}, {3, 1}};
ll f[MAXN][8];

int main() {
	register int i, j;
	scanf("%s", S + 1); N = strlen(S + 1);
	f[1][0] = 1;
	for(i = 1; i <= N; ++i)
		for(j = 0; j < 8; ++j) {
			if(S[i] != '0') (f[i + 1][To[j][1]] += f[i][j]) %= Mod;
			if(S[i] != '1') (f[i + 1][To[j][0]] += f[i][j]) %= Mod;
		}
	printf("%lld\n", (f[N + 1][1] + f[N + 1][2]) % Mod);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0, i##_len = (n); i < i##_len; i++)
#define reps(i, s, n) for(int i = (s), i##_len = (n); i < i##_len; i++)
#define rrep(i, n) for(int i = (n) - 1; i >= 0; i--)
#define rreps(i, e, n) for(int i = (n) - 1; i >= (e); i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)(x).size())
#define uniq(x) (x).erase(unique((x).begin(), (x).end()), (x).end())

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int a, b;
    cin >> a >> b;
    vector<string> ans(100);
    rep(i, 100) {
        rep(ii, 100) {
            ans[i] += ((i >= 50) ? "." : "#");
        }
    }
    rep(i, a - 1) {
        ans[i * 2 / 100 * 2][i * 2 % 100] = '.';
    }
    rep(i, b - 1) {
        ans[99 - i * 2 / 100 * 2][i * 2 % 100] = '#';
    }
    printf("100 100\n");
    rep(i, 100) printf("%s\n", ans[i].c_str());
    return 0;
}


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

int main() {
  int n;
  string s,t;
  cin>>n>>s>>t;
  string ans=s+t;
  for(int i=n; i>=1; i--){
    string s_=s.substr(n-i, i);
    string t_=t.substr(0,i);
    if(s_==t_){ans=s.substr(0,n-i)+t;break;}
  }
  cout<<ans.size();
}

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

using namespace std;

int solve(string s, string t, int n){
    // sの文字のうち, かぶっていない文字の数をiとする
    // 全探索する
    for (int i = 0; i < n; i++){
        if (s.substr(i) == t.substr(0,n-i)) return n + i;
    }

    // n文字すべてかぶらない-> 2*n
    return 2*n;
}

int main(){
    int n;
    cin >> n;
    string s,t;
    cin >> s >> t;

    cout << solve(s,t,n) << endl;
    return 0;
}


#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <algorithm>
#include <bitset>
#include <complex>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include <cassert>
#include <functional>

typedef long long ll;
using namespace std;

#ifndef LOCAL
#define debug(...) ;
#else
#define debug(...) cerr << __LINE__ << " : " << #__VA_ARGS__ << " = " << _tostr(__VA_ARGS__) << endl;

template<typename T>
ostream &operator<<(ostream &out, const vector<T> &v);

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

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

void _tostr_rec(ostringstream &oss) {
  oss << "\b\b \b";
}

template<typename Head, typename... Tail>
void _tostr_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << head << ", ";
  _tostr_rec(oss, forward<Tail>(tail)...);
}

template<typename... T>
string _tostr(T &&... args) {
  ostringstream oss;
  int size = sizeof...(args);
  if (size > 1) oss << "{";
  _tostr_rec(oss, forward<T>(args)...);
  if (size > 1) oss << "}";
  return oss.str();
}
#endif

#define mod 1000000007 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 200010

ll dp[SIZE][2];

int main() {
  int N, A[SIZE];

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

  for (int i = 0; i <= N; i++) dp[i][0] = dp[i][1] = -LLINF;
  dp[0][0] = 0;

  for (int i = 0; i < N; i++) {
    dp[i + 1][0] = max(dp[i][0] + A[i], dp[i][1] - A[i]);
    dp[i + 1][1] = max(dp[i][0] - A[i], dp[i][1] + A[i]);
  }

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

  return 0;
}

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <bitset>
#include <set>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define RREP(i,n) for(int i=n-1;i>=0;i--)
#define FOR(i,k,n) for(int i=(k);i<(int)(n);i++)
#define all(i,n) (i),(i+n)

int dx4[4]={1,0,-1,0};
int dy4[4]={0,-1,0,1};
int dx8[8]={1,0,-1,1,-1,1,0,-1};
int dy8[8]={1,1,1,0,0,-1,-1,-1};
int dx9[9]={0,1,0,-1,1,-1,1,0,-1};
int dy9[9]={0,1,1,1,0,0,-1,-1,-1};

typedef pair<int, int> P;
typedef pair<string, int> SP;
typedef long long ll;
typedef pair<ll, ll> PLL;

const int INF = 1e9;
const ll LLINF = 1e18;
const int MAX_V = 1e6+1;
const ll mod = 1000000007;
// << fixed << setprecision
// --------------------------------------
int n;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin >> n;
  vector<ll> a(n);

  int c = 0;
  ll sum = 0;
  REP(i, n) {
    cin >> a[i];
    sum += abs(a[i]);
    if(a[i] < 0) c++;
  }

  if(c % 2 == 1) {
    ll mi = INF;
    REP(i, n)  {
      mi = min(abs(a[i]), mi);
    }
    sum -= (mi * 2);
  }

  cout << sum << endl;
}


#include <bits/stdc++.h>
#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)
#define _all(arg) begin(arg),end(arg)

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

using namespace std;

int main(void){
	int m, nmin, nmax;
	while(cin>>m>>nmin>>nmax,m,nmin,nmax) {
		int res = 0;
		int n = 0;
		int prev = 0;
		rep(i,m) {
			int cur; cin >> cur;
			if(nmin<=i && i <= nmax) if(chmax(res, prev-cur)) n=i;
			prev = cur;
		}
		cout << n << endl;
	}

	return 0;
}

//#define USE_CPP11
// #define USE_PRINTF

#include <iostream>
#include <iomanip>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <numeric>
#include <complex>
#include <memory>
#include <sstream>

#ifdef USE_CPP11
#include <unordered_map>
#include <unordered_set>
#include <functional>
#endif

#define PRINT(obj) cout << obj << endl
#define REP(i, n) for(int (i) = 0; (i) < (n); i++)
#define SPACE " "

typedef long long ll;

const int INF = 1e9 + 10;

using namespace std;

namespace Scanner {
#ifdef USE_PRINTF
  int    nextInt()    { int    d; scanf("%d" , &d); return d; }
  float  nextFloat()  { float  f; scanf("%f" , &f); return f; }
  double nextDouble() { double f; scanf("%lf", &f); return f; }
  string nextString() { string s; scanf("%s" , &s); return s; }
  ll     nextll()     { ll     l; scanf("%ll", &l); return l; }
#else
  int    nextInt()    { int    d; cin >> d; return d; }
  float  nextFloat()  { float  f; cin >> f; return f; }
  double nextDouble() { double f; cin >> f; return f; }
  string nextString() { string s; cin >> s; return s; }
  ll     nextll()     { ll     l; cin >> l; return l; }
#endif

  string getLine() {
    string input;
    getline(cin, input);
    return input;
  }
};

namespace myLibrary {
  vector<string> split(const string& str, char delim) {
    vector<string> ret;
    size_t current = 0, found;
    while ((found = str.find_first_of(delim, current)) != string::npos) {
      ret.push_back(string(str, current, found - current));
      current = found + 1;
    }
    ret.push_back(string(str, current, str.size() - current));
    return ret;
  }

#ifdef USE_CPP11
  ///
  /// higher-order functional
  /// This is something like map in haskell, python, etc.
  /// Sample usage:
  ///   vector<int> a = {1, 2, 3, 4, 5};
  ///   vector<int> b = myLibrary::_Map<int, int>(a, [](int n){
  ///     return n * n;
  ///   });
  /// Result:
  ///   b = 1, 4, 9, 16, 25
  ///
  template<typename T_IN, typename T_OUT, class Functor>
  vector<T_OUT> _Map(vector<T_IN> src, Functor func) {
    vector<T_OUT> ret;
    for (int i = 0; i < src.size(); i++) {
      ret.push_back(func(src[i]));
    }
    return ret;
  }
#endif

};

/// BEGIN //////////////////////////////////////////////////////////

int main() {
  while (true) {
    int m    = Scanner::nextInt();
    int nmin = Scanner::nextInt();
    int nmax = Scanner::nextInt();

    if (m + nmin + nmax == 0) {
      break;
    }

    vector<int> Ps(m);
    REP(i, m) {
      int p = Scanner::nextInt();
      Ps[i] = p;
    }

    int ans, ans_diff = -1;
    for (int i = nmin - 1; i <= nmax - 1; i++) {
      int diff = Ps[i] - Ps[i + 1];
      if (diff >= ans_diff) {
        ans_diff = diff;
        ans = i;
      }
    }
    PRINT(ans + 1);
  }

  return 0;
}
/// END   //////////////////////////////////////////////////////////


#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
#include <utility>
#include<vector>
#include<iomanip>
#include<map>
#include <queue>
#include<cmath>
#include<cstdio>
#include<iomanip>
#include<set>
#include <bits/stdc++.h>

using namespace std;
using ll = long long int;

#define REP(i,n) for(ll i=0;i<(ll)(n);i++) //REP(i, 5) cout<<i;
#define REPD(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define MOD 1000000007 //10^9+7
//#define MOD 1

ll gcd(ll a, ll b) {
  ll tmp;
  if ( b > a) {
    tmp = a;
    a = b;
    b = tmp;
  }
  while (a % b !=0) {
    tmp = b;
    b = a % b;
    a = tmp;
  }
  return b;
}

const int MAX = 1000;

ll table[MAX][MAX];

// テーブルを作る前処理
void COMinit() {
    table[0][0] = table[0][1] = 1;
    FOR(i, 1, MAX-1){
      FOR(j, 0, i+1){
        if(j==0) table[i][j] = 1;
        else if(j == i+1) table[i][j] = 1;
        else table[i][j] = table[i-1][j-1]+table[i-1][j];
      }
    }
}

// 二項係数計算
ll COM(ll n, ll k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return table[n-1][k];
}

void sosuu(ll n, vector<ll> &v){

  vector<ll> num(n, 0);

  FOR(i, 1, sqrt(n)){
    if(num[i]==0){
      FOR(j, 0, n/i){
        num[i+(j*i)] = 1;
      }
    }
  }
  REP(i, n){
    if(num[i]==0) v.push_back(i+1);
  }
}

int main(void){

   double n;
   cin>>n;

    cout<<(n-2)*180.0<<endl;
  return 0;
}

#include <bits/stdc++.h>
#define sz(arr) (int)arr.size()
#define all(arr) arr.begin(), arr.end()

using namespace std;

void _cin() {}
template <class Head, class... Tail>
void _cin(Head&& head, Tail&&... tail) {
  cin >> head;
  _cin(forward<Tail>(tail)...);
}

#define Cin(T, ...) \
  T __VA_ARGS__;    \
  _cin(__VA_ARGS__)

int main() {
  Cin(int, n);
  cout << 180 * (n - 2) << endl;

  return 0;
}


#include<iostream>
using namespace std;

int F[102][102];

void
DFS (int Y, int X, int A)
{
  if (F[Y][X] != A)
    return;

  F[Y][X] = 7;

  DFS (Y - 1, X, A);
  DFS (Y, X + 1, A);
  DFS (Y + 1, X, A);
  DFS (Y, X - 1, A);
}

int
main ()
{
  int w, h;
  int xs, ys;
  int xg, yg;
  int n;
  int c, d, x, y;

  while (true)
    {
      cin >> w >> h;
      if (w == 0 && h == 0)
	break;
      cin >> xs >> ys;
      cin >> xg >> yg;
      cin >> n;

      for (int i = 0; i < n; i++)
	{
	  cin >> c >> d >> x >> y;
	  if (d == 0)
	    {
	      for (int a = 0; a < 4; a++)
		{
		  for (int b = 0; b < 2; b++)
		    {
		      F[y + b][x + a] = c;
		    }
		}

	    }
	  else
	    {
	      for (int a = 0; a < 2; a++)
		{
		  for (int b = 0; b < 4; b++)
		    {
		      F[y + b][x + a] = c;
		    }
		}
	    }

	}

      if (F[ys][xs] == 1 || F[ys][xs] == 2 || F[ys][xs] == 3
	  || F[ys][xs] == 4 || F[ys][xs] == 5)
	{
	  DFS (ys, xs, F[ys][xs]);
	}

      if (F[yg][xg] == F[ys][xs])
	{
	  cout << "OK" << endl;
	}
      else
	{
	  cout << "NG" << endl;
	}

    }

  return 0;
}

#include<iostream>
#include<cstdio>
#include<vector>

#define INF 999999999
#define ll long long

using namespace std;

const int MAX_N = 100000;
const int MAX_M = 500000;

struct edge
{
    int from;  //?????????
    int to;    //??°??????
    int cost;  //??????
};

int d[MAX_N];
edge es[MAX_M];
bool flag;  //???????????????????????????

void shortest_path(int n,int m,int s)   //s???????????????????????????????????????????????¢????±???????
{
    int cnt = 0;
    fill(d,d+n,INF);
    d[s] = 0;
    while(true && cnt < n){
        bool update = false;
        for(int i=0;i<m;i++){
            edge e = es[i];
            if(d[e.from] != INF && d[e.to] > d[e.from] + e.cost){
                d[e.to] = d[e.from] + e.cost;
                update = true;
            }
        }
        if(!update) break;
        cnt++;
    }
    if(cnt == n){
        flag = true;
    }
}

int main()
{
    int i,n,m,s;
    cin >> n;  //????????°
    cin >> m;  //?????°
    cin >> s;  //???????????????
    for(int i=0;i<m;i++){
        scanf("%d",&es[i].from);
        scanf("%d",&es[i].to);
        scanf("%d",&es[i].cost);
    }
    flag = false;
    shortest_path(n,m,s);
    if(!flag){
        for(int i=0;i<n;i++){
            if(d[i] == INF){
                cout << "INF\n";
            }else{
                cout << d[i] << "\n";
            }
        }
    }else{
        cout << "NEGATIVE CYCLE\n";
    }
}


#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cin.ignore();

    while(--n >= 0){
        string s;
        getline(cin, s);
        int i = 0;
        for(;;){
            i = s.find("Hoshino", i);
            if(i == string::npos)
                break;
            s.replace(i, 7, "Hoshina");
        }
        cout << s << endl;
    }
}

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

#define ll long long
#define vvi vector<vector<int>>
#define All(X) X.begin(),X.end()

int main(){
	int n;
	cin >> n;
	ll int tmp;
	ll int sum,min,max;
	max = -1000010;
	min = 9999999;
	sum = 0;
	for(int i=0;i<n;i++){
		cin >> tmp;
		if(tmp<min) min = tmp;
		if(tmp>max) max = tmp;
		sum += tmp;
	}
	cout << min <<" " << max << " " << sum << endl;

}


#include <iostream>

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

using namespace std;

int    nextInt()    { int d;      cin >> d;   return d;   }
string nextString() { string str; cin >> str; return str; }

int main() {
  while(true) {
    int N = nextInt();
    int Q = nextInt();
    if (N + Q == 0) break;

    int D[101] = {0};
    REP(i, N) {
      int M = nextInt();
      REP(j, M) {
        int d = nextInt();
        D[d]++;
      }
    }

    int max_d = -1;
    int max_idx;
    REP(i, 101) {
      if (D[i] > max_d) {
        max_d = D[i];
        max_idx = i;
      }
    }
    if (max_d < Q) {
      cout << 0 << endl;
    } else {
      cout << max_idx << endl;
    }
  }
  return 0;
}

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

int main(){
    int n, q;
    while(cin >> n >> q, n != 0 && q != 0){
        map<int,int> c;
        for(int i=0; i<n; ++i){
            int m;
            cin >> m;
            for(int j=0; j<m; ++j){
                int tmp;
                cin >> tmp;
                if(c.find(tmp) == c.end())
                    c.insert(map<int,int>::value_type(tmp,1));
                else
                    ++c[tmp];
            }
        }
        map<int,int>::iterator it = c.begin();
        int max = 0, res = 0;
        while(it!=c.end()){
            if(max < (*it).second && q <= (*it).second){
                max = (*it).second;
                res = (*it).first;
            }
            ++it;
        }
        cout << res << endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 40;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); }
template <typename T> void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
template <typename T> void write(T x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
	write(x);
	puts("");
}
char s[MAXN], a[MAXN], b[MAXN];
int n, dp[MAXN][MAXN]; ll ans;
void work(int pos, int la, int lb) {
	if (pos == n) {
		memset(dp, 0, sizeof(dp)), dp[n][la] = 1;
		for (int i = n; i >= 1; i--)
		for (int j = max(0, i - lb), k = i - j; j <= la && j <= i; j++, k--) {
			if (s[i] == a[j]) dp[i - 1][j - 1] += dp[i][j];
			if (s[i] == b[k]) dp[i - 1][j] += dp[i][j];
		}
		ans += dp[0][0];
		return;
	}
	a[la + 1] = s[pos];
	work(pos - 1, la + 1, lb);
	b[lb + 1] = s[pos];
	work(pos - 1, la, lb + 1);
}
int main() {
	read(n), scanf("%s", s + 1);
	work(n * 2, 0, 0);
	writeln(ans);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=55,mod=1e9+7,inf=2000000000;
int n,a[N];
char s[N];
unordered_map<ll,int>vis[20][20];
int main()
{
    scanf("%d",&n);
    scanf("%s",s+1);
    int up=1<<n;
    for(int i=0;i<up;i++)
    {
        ll sum1=0,sum2=0,a=__builtin_popcount(i),b=n-a;
        for(int j=1;j<=n;j++)
            if(i>>j-1&1)
            sum1=(sum1*2333%mod+s[j]-'a')%mod;
            else sum2=(sum2*2333%mod+s[j]-'a')%mod;
        //cout<<a<<' '<<b<<' '<<sum1*inf+sum2<<endl;
        vis[a][b][sum1*inf+sum2]++;
    }
    reverse(s+1,s+1+n+n);
    ll ans=0;
    for(int i=0;i<up;i++)
    {
        ll sum1=0,sum2=0,a=__builtin_popcount(i),b=n-a;
        for(int j=1;j<=n;j++)
            if(i>>j-1&1)
            sum1=(sum1*2333%mod+s[j]-'a')%mod;
            else sum2=(sum2*2333%mod+s[j]-'a')%mod;
        //cout<<a<<' '<<b<<' '<<sum1*inf+sum2<<endl;
        ans+=vis[b][a][sum2*inf+sum1];
    }
    printf("%lld\n",ans);
}


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

const long long MOD = 998244353;

long long fact[3000005];

long long powmod(long long a, long long b){
    long long x = 1;
    long long y = a;
    while(b){
        if(b&1){ x = (x*y)%MOD; }
        y = (y*y)%MOD;
        b >>= 1;
    }
    return x;
}

inline long long ncr(long long a, long long b){
    return fact[a]*powmod((fact[a-b]*fact[b])%MOD, MOD-2)%MOD;
}

long long solve(int N, int sum, int k){
    // exactly N non-negative integers
    // the sum is the variable sum
    // exactly k odd
    if((sum-k)&1){return 0;}
    if(sum-k<0){return 0;}

    // Let's make the k odd integers non-negative even integers
    // Then, the sum becomes (sum-k) and we can then divide by 2 to normalise the non-negative integers
    // The integers can now be any non-negative integer, without any other restriction, so formula can be used.
    // (((sum-k)/2)+(N-1)) choose (N-1) ways to make such integers

    // Don't forget that there are N choose k ways to arrange the odd integers.
    return ncr(N, k)*ncr( ((sum-k)>>1)+(N-1) , N-1)%MOD;
}

int main(){
    int N, M;
    scanf("%d%d", &N, &M);

    fact[0] = 1;
    for(int i = 1; i <= 3000004; i ++){
        fact[i] = (fact[i-1]*i)%MOD;
    }

    // Let us ignore the maximum integer rule and count the number of ways
    // There can only be at most M odd integers.
    long long temp1 = 0;
    for(int k = 0; k <= min(M, N); k ++){
        temp1 += solve(N, 3*M, k);
        //printf("solve(%d, %d, %d)=%lld\n", N, 3*M, k, solve(N, 3*M, k));
    }
    temp1 %= MOD;

    // Notice that the maximum integer cannot exceed 2M. There can only be a maximum of one violation
    // because 2M+2M = 4M > 3M, a contradiction. Hence, there are N ways to choose the violating integer.
    // Then, we can subtract 2M from the offending integer. 2M is even, hence there is no effect on parity.
    // Conditions remain the same as before, except that the offending integer must be positive.
    long long temp2 = 0;
    for(int k = 0; k <= min(M, N); k ++){
        temp2 += solve(N, M, k);
    }
    temp2 %= MOD;
    temp2=temp2*N%MOD;

    // Now, we count number of ways such that the offending integer is 0 because we have over-subtracted those cases.
    // There are only N-1 integers left since the offending integer can be removed, and that the number of odd
    // integers would remain the same since M is even.
    long long temp3 = 0;
    for(int k = 0; k <= min(M, N-1); k ++){
        temp3 += solve(N-1, M, k);
    }
    temp3 %= MOD;
    temp3=temp3*N%MOD;

    //printf("temp1=%lld temp2=%lld temp3=%lld\n", temp1, temp2, temp3);

    long long ans = (temp1-temp2+temp3+MOD*3)%MOD;
    printf("%lld", ans);
    return 0;
}

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

const int MOD=998244353;
const int MAX=200005;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}
// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

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

  ll ans=0;
  ll a=m;
  rep(i,n-1-k) a=a*(m-1)%MOD;
  rep(i,k+1){
    ans=(ans+COM(n-1,k-i)*a%MOD)%MOD;
    a=a*(m-1)%MOD;
  }
  cout<<ans<<endl;
  return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define _GLIBCXX_DEBUG
#define all(x) x.begin(), x.end()
using namespace std;
typedef long long ll;
typedef pair<int, int> pair;
const int inf = 1000000000; //10^9
const ll inff = 1000000000000000000; //10^18

int main(){
    string s;
    cin >> s;
    cout << "2018/01/" << s[8] << s[9] << endl;

    return 0;
}

#include<stdio.h>

int main()
{
	int day,month,year;
	scanf("%d/%d/%d",&year,&month,&day);
	printf("%d/%.2d/%.2d",year+1,month,day);

	return 0;
}