import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author madi.sagimbekov
 */
public class C1159C {

    private static BufferedReader in;
    private static BufferedWriter out;

    private static List<Integer>[] list;
    private static int[] arr;
    private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    private static boolean[] used;

    public static void main(String[] args) throws IOException {
        open();

        arr = readInts();
        int n = arr[0];
        int m = arr[1];
        long[] min = readLongs();
        long[] max = readLongs();

        Arrays.sort(min);
        Arrays.sort(max);

        long ans = 0;
        for (int i = 0; i < n; i++) {
            ans += min[i] * m;
        }

        boolean all = false;
        boolean no = false;
        long maxMin = min[n - 1];
        for (int i = 0; i < m; i++) {
            if (max[i] == maxMin) {
                all = true;
            }
            if (max[i] < maxMin) {
                no = true;
            }

            ans -= maxMin;
            ans += max[i];
        }

        if (no) {
            out.write("-1\n");
            close();
            return;
        }

        if (all) {
            out.write(ans + "\n");
        } else {
            if (n < 2) {
                out.write("-1\n");
            } else {
                ans = ans - min[n - 2] + min[n - 1];
                out.write(ans + "\n");
            }
        }

        close();
    }

    private static int[] readInts() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
    }

    private static int readInt() throws IOException {
        return Integer.parseInt(in.readLine());
    }

    private static long[] readLongs() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray();
    }

    private static long readLong() throws IOException {
        return Long.parseLong(in.readLine());
    }

    private static double[] readDoubles() throws IOException {
        return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray();
    }

    private static double readDouble() throws IOException {
        return Double.parseDouble(in.readLine());
    }

    private static String readString() throws IOException {
        return in.readLine();
    }

    private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException {
        List<Integer>[] list = new ArrayList[n + 1];
        for (int i = 0; i <= n; i++) {
            list[i] = new ArrayList<>();
        }

        for (int i = 0; i < m; i++) {
            int[] e = readInts();
            list[e[0]].add(e[1]);
            list[e[1]].add(e[0]);
        }

        return list;
    }

    private static void open() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new BufferedWriter(new OutputStreamWriter((System.out)));
    }

    private static void close() throws IOException {
        out.flush();
        out.close();
        in.close();
    }

}

n, m = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a.sort()
b.sort()
if a[-1] > b[0]:
    print(-1)
    exit()

if a[-1] == b[0]:
    print(sum(b) + sum(a[:-1]) * m)
else:
    print(sum(b) + a[-1] + sum(a[:-1]) * m - a[-2])


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class D
{
    private static final int m = 13;
    private static int [][] p;
    private static Comparator<int[]> cmp = new Comparator<int[]>() {

        @Override
        public int compare(int[] a, int[] b) {
            if(a[0] != b[0])
                return Integer.compare(a[0], b[0]);
            return Integer.compare(a[1], b[1]);
        }
    };
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        char [] str = reader.readLine().toCharArray();
        char [] st = reader.readLine().toCharArray();
        char [] en = reader.readLine().toCharArray();

        int [] zst = Z(str, st);
        int [] zen = Z(str, en);

        boolean [] stGood = new boolean[str.length];
        for(int i = 0 ; i < str.length ; i++)
            if(zst[i+st.length+1] == st.length)
                stGood[i] = true;

        boolean [] enGood = new boolean[str.length];
        for(int i = 0 ; i < str.length ; i++)
            if(zen[i+en.length+1] == en.length)
                enGood[i+en.length-1] = true;

        int n = str.length;
        p = new int[m][n];
        for(int i = 0 ; i < n ; i++)
            p[0][i] = str[i];

        int [][] order = new int[n][3];
        for(int k = 1 ; k < m ; k++)
        {
            for(int i = 0 ; i < n ; i++)
            {
                order[i][0] = p[k-1][i];
                order[i][1] = i + (1<<(k-1)) < n ? p[k-1][i+(1<<(k-1))] : -1;
                order[i][2] = i;
            }

            Arrays.sort(order, cmp);

            for(int i = 0 ; i < n ; i++)
                p[k][order[i][2]] = i > 0 && order[i][0] == order[i-1][0] && order[i][1] == order[i-1][1] ? p[k][order[i-1][2]] : i;
        }

        int [] suffixes = new int[n];
        for(int i = 0 ; i < n ; i++)
            suffixes[p[m-1][i]] = i;

        int res = 0;
        for(int i = 0 ; i < n ; i++)
        {
            int a = suffixes[i];
            if(stGood[a])
                for(int b = a ; b < n ; b++)
                    if(enGood[b])
                        if(b-a+1 >= st.length)
                            if(b-a+1 >= en.length)
                                if(i+1 >= n || lcp(a, suffixes[i+1]) < b-a+1)
                                    res++;
        }

        System.out.println(res);
    }

    private static int lcp(int x, int y)
    {
        int n = p[0].length;
        if(x == y)
            return n-x;

        int res = 0;
        for(int k = m-1 ; k >= 0 ; k--)
            if(x + (1<<k) <= n && y + (1<<k) <= n && p[k][x] == p[k][y])
            {
                res += 1<<k;
                x += 1<<k;
                y += 1<<k;
            }

        return res;
    }

    private static int [] Z(char [] a, char [] b)
    {
        char [] str = (new String(b)+"$"+new String(a)).toCharArray();

        int n = str.length;
        int left = 0, right = 0;

        int [] z = new int[n];
        for(int i = 1 ; i < n ; i++)
        {
            if(i > right)
            {
                left = right = i;
                while(right < n && str[right] == str[right-left])
                    right++;
                z[i] = right-left;
                right--;
            }
            else
            {
                int k = i - left;
                if(z[k] < right-i)
                    z[i] = z[k];
                else
                {
                    left = i;
                    while(right < n && str[right] == str[right-left])
                        right++;
                    z[i] = right-left;
                    right--;
                }
            }
        }

        return z;
    }
}

from functools import cmp_to_key

def calc_lcp(s, sa):
    rank = [0 for _ in range(len(s))]
    for i in range(len(s)):
        rank[sa[i]] = i
    lcp = [0 for _ in range(len(s) - 1)]
    h = 0
    for i in range(len(s)):
        if rank[i] < len(s) - 1:
            while max(i, sa[rank[i] + 1]) + h < len(s) and s[i + h] == s[sa[rank[i] + 1] + h]:
                h += 1
            lcp[rank[i]] = h
            if h > 0:
                h -= 1
    return lcp, rank

def suffix_array(s):
    sa = [i for i in range(len(s))]
    rank = [ord(s[i]) for i in range(len(s))]
    k = 1
    while k < len(s):
        key = [0 for _ in range(len(s))]
        base = max(rank) + 2
        for i in range(len(s)):
            key[i] = rank[i] * base + (rank[i + k] + 1 if i + k < len(s) else 0)
        sa.sort(key=(lambda i: key[i]))

        rank[sa[0]] = 0
        for i in range(1, len(s)):
            rank[sa[i]] = rank[sa[i - 1]] if key[sa[i - 1]] == key[sa[i]] else i
        k *= 2
    # for i in sa:
    #     print(s[i:])
    return sa

def kmp(s, p):
    pi = [0 for _ in range(len(p))]
    k = 0
    for i in range(1, len(p)):
        while k > 0 and p[k] != p[i]:
            k = pi[k - 1]
        if p[k] == p[i]:
            k += 1
        pi[i] = k

    k = 0
    resp = []
    for i in range(len(s)):
        while k > 0 and p[k] != s[i]:
            k = pi[k - 1]
        if p[k] == s[i]:
            k += 1
        if k == len(p):
            resp.append(i - len(p) + 1)
            k = pi[k - 1]
    return resp

def lower_bound(list, value):
    left = 0
    right = len(list)
    while left < right:
        mid = int((left + right) / 2)
        if list[mid] < value:
            left = mid + 1
        else:
            right = mid
    return left

s = input()
start = input()
end = input()

indStart = kmp(s, start)
indEnd = kmp(s, end)

if len(indStart) == 0 or len(indEnd) == 0:
    print(0)

else:
    sa = suffix_array(s)
    lcp, rank = calc_lcp(s, sa)

    ind = rank[indStart[0]]
    for st in indStart:
        ind = min(ind, rank[st])

    resp = len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, len(start) - len(end)))
    while ind < len(lcp) and lcp[ind] >= len(start):
        ind += 1
        resp += len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, max(lcp[ind - 1] + 1, len(start)) - len(end)))

    print(resp)


n = int(input().strip())
xm,ym = (0,0)
for i in range(2*n):
    x,y = list(map(int,input().strip().split()))
    xm+=x
    ym+=y
print(xm//(n), ym//(n))

#include <bits/stdc++.h>
using namespace std;
set<int> s;
vector<int> v;
vector<int> v1;
int main() {
  ios::sync_with_stdio(false);
  cout.tie(NULL);
  cin.tie(NULL);
  int n;
  cin >> n;
  int o_x = -100000000, o_y = -100000000;
  int c_x = 100000000, c_y = 100000000;
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    if (x > o_x) {
      o_x = x;
    }
    if (y > o_y) {
      o_y = y;
    }
  }
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    if (x < c_x) {
      c_x = x;
    }
    if (y < c_y) {
      c_y = y;
    }
  }
  cout << o_x + c_x << " " << o_y + c_y;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int n, m, q, p, a, b, c, d, f[100000];
int max(int x, int y) {
  if (x > y)
    return x;
  else
    return y;
}
int main() {
  scanf("%d%d%d%d", &n, &m, &q, &p);
  for (int i = q; i <= n; i++) f[i] = i / q * p;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &a, &b, &c, &d);
    for (int j = 1; j <= (a / b); j++)
      for (int k = n; k >= c; k--) f[k] = max(f[k], f[k - c] + d);
  }
  printf("%d", f[n]);
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Buns {

	static int n, m, c0, d0;
	static int[] a, b, c;
	static long[] d;
	static long[][] dp;

	static long solve(int curr, int i) {
		if (curr == 0 || i == m)
			return 0;
		if (dp[curr][i] != -1)
			return dp[curr][i];
		long ans = 0;
		int num = 1;
		while (num * c0 <= curr) {
			ans = Math.max(ans, num * d0 + solve(curr - num * c0, i));
			num++;
		}
		num = 1;
		while (num * b[i] <= a[i] && num * c[i] <= curr) {
			ans = Math.max(ans, num * d[i] + solve(curr - num * c[i], i + 1));
			num++;
		}
		ans = Math.max(ans, solve(curr, i + 1));
		return dp[curr][i] = ans;
	}

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		sc = new StringTokenizer(br.readLine());
		n = nxtInt();
		m = nxtInt();
		c0 = nxtInt();
		d0 = nxtInt();
		a = new int[m];
		b = new int[m];
		c = new int[m];
		d = new long[m];
		for (int i = 0; i < m; i++) {
			a[i] = nxtInt();
			b[i] = nxtInt();
			c[i] = nxtInt();
			d[i] = nxtLng();
		}
		dp = new long[n + 1][m];
		for (int i = 0; i < n + 1; i++)
			Arrays.fill(dp[i], -1);
		out.println(solve(n, 0));
		br.close();
		out.close();
	}

	static BufferedReader br;
	static StringTokenizer sc;

	static String nxtTok() throws IOException {
		while (!sc.hasMoreTokens()) {
			String s = br.readLine();
			if (s == null)
				return null;
			sc = new StringTokenizer(s.trim());
		}
		return sc.nextToken();
	}

	static int nxtInt() throws IOException {
		return Integer.parseInt(nxtTok());
	}

	static long nxtLng() throws IOException {
		return Long.parseLong(nxtTok());
	}

	static double nxtDbl() throws IOException {
		return Double.parseDouble(nxtTok());
	}

	static int[] nxtIntArr(int n) throws IOException {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = nxtInt();
		return a;
	}

	static long[] nxtLngArr(int n) throws IOException {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nxtLng();
		return a;
	}

	static char[] nxtCharArr() throws IOException {
		return nxtTok().toCharArray();
	}
}


/**
 * author: derrick20
 * created: 1/25/21 12:29 AM
 */
import java.io.*;
import java.util.*;
import static java.lang.Math.*;

public class CompanyAcquisitions {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        int N = sc.nextInt();
        int[] children = new int[N + 1];
        for (int i = 1; i <= N; i++) {
            int par = sc.nextInt();
            if (par != -1) {
                children[par]++;
            }
        }
        long[] twoPow = new long[N + 1];
        twoPow[0] = 1;
        for (int i = 1; i <= N; i++) {
            twoPow[i] = 2 * twoPow[i - 1] % mod;
        }
        long M0 = 0;
        for (int c : children) {
            M0 = (M0 + twoPow[c] - 1) % mod;
        }
        long Mt = twoPow[N - 1] - 1;
        long Et = (Mt - M0 + mod) % mod;
        out.println(Et);
        out.close();
    }

    static long mod = (long) 1e9 + 7;

    static class FastScanner {
        private int BS = 1 << 16;
        private char NC = (char) 0;
        private byte[] buf = new byte[BS];
        private int bId = 0, size = 0;
        private char c = NC;
        private double cnt = 1;
        private BufferedInputStream in;

        public FastScanner() {
            in = new BufferedInputStream(System.in, BS);
        }

        public FastScanner(String s) {
            try {
                in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
            } catch (Exception e) {
                in = new BufferedInputStream(System.in, BS);
            }
        }

        char getChar() {
            while (bId == size) {
                try {
                    size = in.read(buf);
                } catch (Exception e) {
                    return NC;
                }
                if (size == -1) return NC;
                bId = 0;
            }
            return (char) buf[bId++];
        }

        int nextInt() {
            return (int) nextLong();
        }

        long nextLong() {
            cnt = 1;
            boolean neg = false;
            if (c == NC) c = getChar();
            for (; (c < '0' || c > '9'); c = getChar()) {
                if (c == '-') neg = true;
            }
            long res = 0;
            for (; c >= '0' && c <= '9'; c = getChar()) {
                res = (res << 3) + (res << 1) + c - '0';
                cnt *= 10;
            }
            return neg ? -res : res;
        }

        double nextDouble() {
            boolean neg = false;
            if (c == NC) c = getChar();
            for (; (c < '0' || c > '9'); c = getChar()) {
                if (c == '-') neg = true;
            }
            double cur = nextLong();
            if (c != '.') {
                return neg ? -cur : cur;
            } else {
                double frac = nextLong() / cnt;
                return neg ? -cur - frac : cur + frac;
            }
        }

        String next() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c > 32) {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        String nextLine() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c != '\n') {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        boolean hasNext() {
            if (c > 32) return true;
            while (true) {
                c = getChar();
                if (c == NC) return false;
                else if (c > 32) return true;
            }
        }
    }
    static void ASSERT(boolean assertion, String message) {
        if (!assertion) throw new AssertionError(message);
    }
    static void ASSERT(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
}

#include <bits/stdc++.h>
struct {
  inline operator int() {
    int x;
    return scanf("%d", &x), x;
  }
  inline operator long long() {
    long long x;
    return scanf("%lld", &x), x;
  }
  template <class T>
  inline void operator()(T &x) {
    x = *this;
  }
  template <class T, class... A>
  inline void operator()(T &x, A &...a) {
    x = *this;
    this->operator()(a...);
  }
} read;
const int maxn = 505, mod = 1000000007;
int a[maxn];
int tot[maxn];
long long f[maxn];
int main() {
  int n = read;
  for (int i = 1; i <= n; i++) {
    read(a[i]);
    if (a[i] != -1) ++tot[a[i]];
  }
  for (int i = 1; i <= n; i++) f[i] = (f[i - 1] * 2 + 1) % mod;
  long long begin = 0;
  for (int i = 1; i <= n; i++) begin += f[tot[i]];
  begin %= mod;
  long long end = f[n - 1];
  printf("%lld\n", (end - begin + mod) % mod);
}


import java.io.*;
import java.util.*;
import java.math.*;

public class Competitive_1 {

	public static void main(String[] args){
		FastReader in = new FastReader();
		int n=in.nextInt();

		int count = 0;

		count += n/100;
		n%=100;
		count += n/20;
		n%=20;
		count+=n/10;
		n%=10;
		count+=n/5;
		n%=5;
		count+=n/1;
		n%=1;
		System.out.println(count);

	}

	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

}

money=int(input())
number=0
alist=[100,20,10,5,1]
for i in alist:
    number+=money//i
    money=money%i
print(int(number))


#include <bits/stdc++.h>
using namespace std;
long long sum, x, n, k;
long long arr[123456];
long long t[123456];
long long cum[123456];
long long ans[123456];
long long res[123456];
long long bs() {
  int s = 0, e = n, mid;
  while (s < e) {
    mid = (s + e + 1) / 2;
    if (x >= cum[mid] - sum)
      s = mid;
    else
      e = mid - 1;
  }
  return s;
}
int main() {
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &arr[i]);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &t[i]);
    sum += t[i];
    cum[i] = sum;
  }
  sum = 0;
  for (int i = 1; i <= n; i++) {
    x = arr[i];
    k = bs();
    ans[i]++;
    ans[k + 1]--;
    res[k + 1] += arr[i] - (cum[k] - sum);
    sum += t[i];
  }
  for (int i = 1; i <= n; i++) ans[i] += ans[i - 1];
  for (int i = 1; i <= n; i++) cout << ans[i] * t[i] + res[i] << " ";
  cout << endl;
  return 0;
}

import heapq
heap = []
n = int(input())
V = list(map(int, input().split()))
T = list(map(int, input().split()))
tmp = 0
for i in range(n):
    ans = 0
    heapq.heappush(heap, tmp+V[i])
    while len(heap) and heap[0]<=tmp+T[i]:
        ans += heapq.heappop(heap)-tmp
    tmp += T[i]
    ans += T[i]*len(heap)
    print(ans, end=' ')


n = int(input())
if n < 5:
    print((n*(n-1))//2)
else:
    x = n+n-1
    if str(x).count('9') == len(str(x)):
        print(1)
    else:
        ans = 0
        x = len(str(x))
        x = x-1
        z = 10**x
        y = int('9'*x)
        while y <= (n+(n-1)):
            if n >= y:
                ans += y//2
                # print(y//2)
            else:
                ans += (n-(y//2))
                # print(n-(y//2))
            y += z
        print(ans)

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Pranav ps on 16-12-2017.
 */

/**
 * This is the template for all coding problems
 */
public class D {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {
        private static long MOD = (long)(1e9+7);
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long n = in.nextLong();
//            int max9 = 0;
//            long ten = 10;
//            while(ten <= 2*n){
//                max9++;
//                ten *= 10;
//            }
//            long mod = (long)(Math.pow(10,max9));
//            long x = n/mod;
//            long end = n%mod;
//            long num2x = Math.max(0,end - (mod/2-1));
//            if(end == mod-1)
//                num2x--;
//            long numx2 = mod/2;
//            long numx = (end == 0)?0:(mod-1-end-1);
//            if(end == mod-1)
//                numx++;
//            if(max9 == 0)
//                out.println(((n)*(n-1))/2);
//            else
//                out.println(numx2*(x*x) + numx*x + num2x*((long)2)*x + num2x);

            //After Editorial
            long sum = n + n - 1;
            if(sum < 9){
                out.println(n*(n-1)/2);
                return;
            }
            String num = Long.toString(sum);
            int numDigits = num.length();
            long tenPow = (long)(Math.pow(10,numDigits));
            if(sum == tenPow-1){
                out.println(1);
                return;
            }
            tenPow /= 10;
            long nines = tenPow-1;
            long ans = 0;
            for (int i = 0; i < 10; i++) {
                if(nines <= n+1)
                    ans += (nines/2);
                else if(nines > 2*n-1){

                }
                else{
                    ans += 1 + (2*n-1 - nines)/2;
                }
                nines += tenPow;
            }
            out.println(ans);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  unsigned long n;
  cin >> n;
  unsigned long add = 5, multi = 2;
  unsigned long s = 1, i = 0, l = 0, p = 0, r = 0, h = 0;
  if (n < 6) {
    if (n == 1)
      cout << "Sheldon\n";
    else if (n == 2)
      cout << "Leonard\n";
    else if (n == 3)
      cout << "Penny\n";
    else if (n == 4)
      cout << "Rajesh\n";
    else
      cout << "Howard\n";
  } else {
    while (1) {
      s += add;
      if (n < s) {
        cout << "Howard\n";
        break;
      }
      l = s + multi;
      if (n < l) {
        cout << "Sheldon\n";
        break;
      }
      p = l + multi;
      if (n < p) {
        cout << "Leonard\n";
        break;
      }
      r = p + multi;
      if (n < r) {
        cout << "Penny\n";
        break;
      }
      h = r + multi;
      if (n < h) {
        cout << "Rajesh\n";
        break;
      }
      add *= 2;
      multi *= 2;
    }
  }
}

Sheldon Sheldon Sheldon Leonard Rajesh Penny Sheldon Penny Sheldon Leonard Sheldon Sheldon Rajesh Penny Sheldon Leonard Penny Howard Sheldon Rajesh Rajesh Sheldon Penny Leonard Sheldon Penny Sheldon Sheldon Penny Rajesh Sheldon Rajesh Sheldon Howard Leonard Howard Howard Leonard Penny Rajesh Penny Sheldon Leonard Rajesh Howard Sheldon Penny Leonard Rajesh Penny

import java.util.*;
public class doublecola{
	public static void main(String[] args){
		Scanner br = new Scanner(System.in);
		int n = br.nextInt();
		String[] names = new String[5];
		names[0] = "Sheldon";
		names[1] = "Leonard";
		names[2] = "Penny";
		names[3] = "Rajesh";
		names[4] = "Howard";
		int pos = 0;
		int multi = 1;
		int num = 1;
		while(num < n){
			pos++;
			if(pos == 5){
				multi*=2;
				pos = 0;
			}
			num+=multi;
		}
		System.out.println(names[pos]);
	}
}


MOD = 10**9 + 7

s = input()
bcount, count = 0, 0
for c in reversed(s):
    if c == 'b':
        bcount += 1
    else:
        count += bcount
        bcount *= 2
        if bcount > 2**62:
            bcount %= MOD

print(count % MOD)

xxx" where each input is a string of letters 'a' and 'b' with length from 1 to 40 tokens:

```

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
const long long MOD = 1e9 + 7;
long long dp[MAXN];
int main() {
  dp[0] = 0LL;
  dp[1] = 1LL;
  for (int(i) = (2); (i) < (MAXN); (i)++) {
    dp[i] = (dp[i - 1] * 2LL + 1LL) % MOD;
  }
  string s;
  cin >> s;
  int a_ctr = 0, b_ctr = 0;
  long long res = 0;
  for (int(i) = (0); (i) < (s.length()); (i)++) {
    if (s[i] == 'a') {
      ++a_ctr;
    } else {
      res = (res + dp[a_ctr]) % MOD;
    }
  }
  cout << res;
  return 0;
}


def read_input():
    line = input().strip().split()
    m = int(line[0])
    week = int(line[1])
    days31 = {1,3,5,7,8,10,12}
    if m == 2:
        days = 28
    elif m in days31:
        days = 31
    else:
        days = 30
    z = (days + week - 1)
    return z//7 if z % 7 == 0 else z//7 + 1

if __name__ == "__main__":
    print(read_input())

#include <bits/stdc++.h>
using namespace std;
int cs[12];
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int m, d;
  cin >> m >> d;
  int ans = 1;
  int mes = 30;
  if (m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12)
    mes++;
  if (m == 2) mes = 28;
  for (int i = 1; i <= d; i++) cs[i]++;
  for (int i = 1; i < mes; i++) {
    cs[(i + d) % 7]++;
  }
  int ma = -10;
  for (int i = 0; i < 9; i++) {
    if (cs[i] > ma) ma = cs[i];
  }
  cout << ma << endl;
  return 0;
}


#include <bits/stdc++.h>
long long f1, f2;
int main() {
  f1 = 1;
  f2 = 2;
  long long N;
  scanf("%lld", &N);
  long long x = f1 + f2, ans = 1;
  while (x <= N) {
    f1 = f2;
    f2 = x;
    x = f1 + f2;
    ans++;
  }
  printf("%lld\n", ans);
  return 0;
}

n = int(input())
an = 0
a = 1
b = 0
c = 2
while(n >= c):
	b = a
	a = c
	c = a + b
	an+=1
print(an)


#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 + 10;
int a[MAXN], l[MAXN], r[MAXN];
void solve() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
  l[1] = 1;
  for (int i = 2; i <= n; i++) {
    l[i] = (a[i] >= a[i - 1] ? l[i - 1] + 1 : 1);
  }
  r[n] = 1;
  for (int i = n - 1; i >= 1; i--) {
    r[i] = (a[i] >= a[i + 1] ? r[i + 1] + 1 : 1);
  }
  int ans = -1;
  for (int i = 1; i <= n; i++) {
    ans = max(ans, l[i] + r[i] - 1);
  }
  printf("%d\n", ans);
}
int main() {
  solve();
  return 0;
}

import java.io.*;

import java.util.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {

        int n = scanner.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = scanner.nextInt();
        }

        int max = 0;
        int sum = 0;

        for (int i = 1; i < arr.length; i++) {
            if(arr[i] > arr[i-1]){
                max = Math.max(sum,max);
                sum= calLeft(arr,i);
            }else{
                  sum++;
            }
         }
        max = Math.max(sum,max);
        System.out.println(++max);
    }

    private static int calLeft(int[] arr, int i) {
        int sum = 0;
        for (int j = i; j > 0; j--) {
            if(arr[j] >= arr[j-1])
            sum++;
            else
                break;
        }
        return sum;
    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  string s;
  cin >> s;
  int n = s.length();
  int l = 0;
  for (int i = 0; i < n; i++) {
    if (s[i] == tolower(s[i])) l++;
  }
  if (l >= n - l)
    transform(s.begin(), s.end(), s.begin(), ::tolower);
  else
    transform(s.begin(), s.end(), s.begin(), ::toupper);
  cout << s;
}

import java.util.*;
public class upperToLower {
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		String a=sc.next();
		char x[]= a.toCharArray();
		int u=0,l=0;
		for(int i=0;i<x.length;i++) {
			if(Character.isUpperCase(x[i]))u++;
			else l++;
		}
		if(u>l)System.out.println(a.toUpperCase());
		else
			System.out.println(a.toLowerCase());
	}

}


import java.util.ArrayList;
import java.util.Scanner;

public class C {
	static ArrayList<Long> primes;
	static long u=2000;
	static void sieve(){
		primes=new ArrayList<Long>();
		u++;
		ArrayList<Boolean> bs=new ArrayList<Boolean>();
		for(int i=0;i<=u;i++){
			bs.add(true);
		}
		bs.set(0, false);
		bs.set(1, false);
		for(int i=2;i<u;i++){
			if(bs.get(i)){
				for(int j=i*i;j<u;j+=i){
					bs.set(j, false);
				}
				primes.add((long) i);
			}
		}
	}

	public static void main(String[] args) {
		sieve();

		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int count = 0;
		ArrayList<Long> a = new ArrayList<Long>();
		long prime = primes.get(0);

		for(int exp=1;exp<13;exp++){
			for(int i=0;Math.pow(primes.get(i), exp)<=n;i++){
				a.add((long) Math.pow(primes.get(i), exp));
				count++;
			}
		}

	/*	int z = 4;
		while( z < n){
			a.add(z);
			z = z*2;
			count++;
		}*/

		System.out.println(count);
		for(int i = 0; i<count; i++){
			System.out.print(a.get(i));
			System.out.print(' ');
		}

	}
}

def get_primes(n):
    numbers = set(range(n, 1, -1))
    primes = []
    while numbers:
        p = numbers.pop()
        primes.append(p)
        numbers.difference_update(set(range(p*2, n+1, p)))
    return primes

n = int(input())

l = get_primes(n+1)

ans = []
for x in l:
    p = x
    while(p<=n):
        ans.append(p)
        p*=x

print(len(ans))
for x in ans:
    print(x, end=' ')


#include <bits/stdc++.h>
using namespace std;
long long int MOD = (1e9) + 7;
inline void fastIO() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
}
int main() {
  fastIO();
  int n, l, r, dif, ans = 0;
  cin >> n >> l >> r >> dif;
  vector<int> problems(n);
  for (int i = 0; i < n; i++) {
    cin >> problems[i];
  }
  for (int i = 0; i < pow(2, n); i++) {
    int bitmask = i, sum = 0, minn = 1e9, maxx = 0, num = 0;
    for (int j = 0; j < n; j++) {
      if (bitmask & (1 << (j))) {
        sum += problems[j], num++;
        minn = min(minn, problems[j]);
        maxx = max(maxx, problems[j]);
      }
    }
    bool valid = (sum >= l && sum <= r) && (maxx - minn >= dif) && (num >= 2);
    if (valid) ans++;
  }
  cout << ans << endl;
}

import java.io.*;
import java.util.*;
public class CFB
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        long L = sc.nextLong(), R = sc.nextLong(), X = sc.nextLong();
        int a[] = new int[N];
        int count = 0;
        for(int i=0;i<N;i++)
            a[i] = sc.nextInt();
        for (int i = 0; i < (int) Math.pow(2, N); i++) {
            int subset[] = new int[N], copy = i, index = N - 1;
            long cost = 0, min=Long.MAX_VALUE, max = Long.MIN_VALUE;
            while (copy > 0) {
                subset[index--] = copy % 2;
                copy /= 2;
            }
            for (int j = 0; j < N; j++) {
                if (subset[j] == 1) {
                    if(a[j]> max)
                        max=a[j];
                    if(a[j]<min)
                        min=a[j];
                    cost += a[j];
                }
            }
            if(cost>=L && cost<=R && max-min>=X)
                count++;
        }
        System.out.println(count);
    }
}


n = int(input())

knowledge = input()

count = 0

keyHash = {}

for i in range((2*n) -2):
    if i%2 == 0:
        key = knowledge[i]

        if key in keyHash: keyHash[key]+=1

        else: keyHash[key] = 1

    else:
        door = knowledge[i]

        reqKey = chr(ord(door)+ 32)

        if reqKey in keyHash and keyHash[reqKey] > 0: keyHash[reqKey]-=1

        else: count+=1

print(count)


import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;

public class Watermelon {
	public static void main(String[] args) throws IOException{
		Main m=new Main();
		m.solve();
	}
	}
class Main{

	static int[] temp=new int[100];
	 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
	 private int[] array;
	    private int[] tempMergArr;
	    private int length;

	    StringTokenizer stringTokenizer;

	     String next() throws IOException {
	        while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
	            stringTokenizer = new StringTokenizer(reader.readLine());
	        }
	        return stringTokenizer.nextToken();
	    }

	    int nextInt() throws IOException {
	        return Integer.parseInt(next());
	    }

	    long nextLong() throws IOException {
	        return Long.parseLong(next());
	    }
	    int n=0;
	    ArrayList<Counti> list=new ArrayList<>();
	    void solve() throws IOException  {

			int mod = 1000000007;
			Scanner scan = new Scanner(System.in);
			long a=scan.nextInt(),b= scan.nextInt();
			long answer = 0;
			for(long i=1;i<=a;i++)
			{
				long c = (i*b+1)%mod;
				long d = (b*(b-1)/2)%mod;
				answer=(answer+c*d)%mod;
			}
			System.out.println(answer);
	    }
	    public  int dp(int i,int count){
	    	System.out.println(i+" "+count);
	    	if((i)==list.size()||count==0)
	    		{System.out.println("Hey");return 0;}
	        int choice1=dp(i+1,count);
	    	int choice2=0;
	    //	if(i!=(list.size()-1))
	   // 	System.out.println(list.get(i).j+" "+list.get(i+1).j);
	        int x=dp(i+1,count-1);
	        if(i+1<list.size()){
	    	if(list.get(i).j<=list.get(i+1).i)
    		    choice2+=(x+(list.get(i).i+list.get(i).j));
	    	else
	    		choice2=(list.get(i).i+list.get(i).j);
	        }
	        else
	        	choice2=(list.get(i).i+list.get(i).j);
	  //      if(i==list.size()-1)
	   //     	choice2+=(dp(i+1,count-1)+(list.get(i).i+list.get(i).j));
	    	System.out.println(choice2);
	     return Math.max(choice1,choice2);
	    }

	      public static double median(double[] m) {
	    	    int middle = m.length/2;
	    	    if (m.length%2 == 1) {
	    	        return m[middle];
	    	    } else {
	    	        return (m[middle-1] + m[middle]) / 2.0;
	    	    }
	    	}
	      private static int add(int x,int y){
	    	  if(x==0&&y==1)
	    		  return 1;
	    	  if(x==1&&y==0)
	    		  return 1;
	    	  if(x==0&&y==0)
	    		  return 0;
	    	  if(x==1&&y==1)
	    		  return 0;
	    	   return 0;
	      }
	      private static int[] column(int[] arr){
	    	  for(int i=0;i<arr.length;i++)
	    		  arr[i]=(1-arr[i]);
	    	  return arr;
	      }
          private static int[] row(int[] arr){
        	  for(int i=0;i<arr.length;i++)
	    		  arr[i]=(1-arr[i]);
        	  return arr;
          }
	private static int gcd(int a, int b)
	{
	    while (b > 0)
	    {
	    	int temp = b;
	        b = a % b; // % is remainder
	        a = temp;
	    }
	    return a;
	}
	private static int lcm(int a, int b)
	{
	    return a * (b / gcd(a, b));
	}
	static int[] toFractionPos(int x,int y){
		int a=gcd(x,y);
		int[] arr={x/a,y/a};
		//display(arr);
		return arr;
	}

	static void display(int[][] arr){
		for(int i=0;i<arr.length;i++){
			for(int j=0;j<arr[i].length;j++){
				System.out.print(arr[i][j]+" ");
		}
			System.out.println();
		}
		System.out.println();
	}

	 static void display(String[] arr){
			for(int i=0;i<arr.length;i++){
				System.out.println(arr[i]+" ");
			}
			//System.out.println();

	 }
	 static void display(int[] arr){
		 for(int i=0;i<arr.length;i++)
				System.out.print(arr[i]+" ");
		System.out.println();
		 }
		 static void display(double[] arr){
		 	   for(int i=0;i<arr.length;i++){
		 		   System.out.print(arr[i]+" ");
		 	   }
		 	   System.out.println();
	    }
	 static void display(char[] arr){
		// System.out.println();
		 int t=0;
			for(int i=0;i<arr.length;i++){
				if(arr[i]!='0'){t=i;break;}
			}
			while(t!=arr.length){
				System.out.print(arr[t]);
				t++;
			}
			System.out.println();

		  }
	 static String str(char[] carr){
		 String str="";
		 for(int i=0;i<carr.length;i++){
			    str=str+carr[i];
			}
		 return str;
	 }
	    public void sort(int inputArr[]) {
	        this.array = inputArr;
	        this.length = inputArr.length;
	        this.tempMergArr = new int[length];
	        doMergeSort(0, length - 1);
	    }

	    private void doMergeSort(int lowerIndex, int higherIndex) {

	        if (lowerIndex < higherIndex) {
	            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
	            // Below step sorts the left side of the array
	            doMergeSort(lowerIndex, middle);
	            // Below step sorts the right side of the array
	            doMergeSort(middle + 1, higherIndex);
	            // Now merge both sides
	            mergeParts(lowerIndex, middle, higherIndex);
	        }
	    }

	    private void mergeParts(int lowerIndex, int middle, int higherIndex) {

	        for (int i = lowerIndex; i <= higherIndex; i++) {
	            tempMergArr[i] = array[i];
	        }
	        int i = lowerIndex;
	        int j = middle + 1;
	        int k = lowerIndex;
	        while (i <= middle && j <= higherIndex) {
	            if (tempMergArr[i] <= tempMergArr[j]) {
	                array[k] = tempMergArr[i];
	                i++;
	            } else {
	                array[k] = tempMergArr[j];
	                j++;
	            }
	            k++;
	        }
	        while (i <= middle) {
	            array[k] = tempMergArr[i];
	            k++;
	            i++;
	        }

	    }
}

 class  Count implements Comparable {
    	    String i;
    	    String j;
    	    String k;
    	    String l;
    	    Count(String i,String j){
    	        this.j=j;
    	        this.i=i;
    	        this.l=j;
    	        this.k=i;
        }
    	    void display(){
    	    	System.out.println(i+" "+j);
    	    }

    	    	@Override
    		public int compareTo(Object o) {
    			// TODO Auto-generated method stub
    			Count c=(Count)o;
    			if(j.compareTo(j)>0)
    				return 1;
    			else if(j.compareTo(j)<0)
    				return -1;
    			else{
    				return 0;

    			}
    		}

    	}

 class  Counti implements Comparable {
    	    Integer i;
    	    int j;
    	    Counti(int i,int j){
    	        this.j=j;
    	        this.i=i;
    	    }
    	    void display(){
    	    	System.out.println(i+" "+j);
    	    }

    	    	@Override
    		public int compareTo(Object o) {
    			// TODO Auto-generated method stub
    			Counti c=(Counti)o;
    			if(i.compareTo(c.i)>0)
    				return 1;
    			else if(i.compareTo(c.i)<0)
    	    		return -1;
    			else
    				return 0;
    		}

    	}

 class Extra{
	 ArrayList<Integer> list=new ArrayList<>();

	 void display(){
		 System.out.println(list.size());
		 for(int i=0;i<list.size();i++){
			 System.out.print(list.get(i)+" ");
		 }
		 System.out.println();
	 }
 }

#include <bits/stdc++.h>
using namespace std;
void solve() {
  int a, b;
  cin >> a >> b;
  int mod = ((a - 1) % b + b) % b;
  long long int sum = 0;
  for (int i = a; i <= b; i++) {
    int num = i / b;
    int den = mod + 1;
    if (den >= b) den -= b;
    mod = den;
    if (den == 0) continue;
    if (num % den != 0) continue;
    if (num / den >= 1 && num / den <= a) {
      sum += i;
    }
  }
  printf("%lld\n", sum);
}
void solve1() {
  long long int mod = 1000000007;
  long long int a, b;
  cin >> a >> b;
  long long int sum = 0;
  for (long long int t = 1; t < b; t++) {
    sum =
        (sum + ((b * t) % mod * (((a * (a + 1L)) / 2L) % mod)) % mod + t * a) %
        mod;
    assert(sum >= 0);
  }
  printf("%lld\n", sum);
}
int main() {
  int T = 1;
  for (int i = 1; i <= T; i++) {
    solve1();
  }
  return 0;
}


n,m = map(int, input().split())
s=0
for i in range(n):
    s+=(i+1)*(pow((i+1)/n,m)-pow(i/n,m))
print(s)

#include <bits/stdc++.h>
using namespace std;
double binPow(double x, int k) {
  double res = 1;
  while (k) {
    if (k & 1) res *= x;
    x *= x;
    k >>= 1;
  }
  return res;
}
int main() {
  int n, m;
  double ans = 0;
  cin >> m >> n;
  for (int i = 1; i <= m; i++)
    ans += i * (binPow((i + .0) / m, n) - binPow((i - 1 + .0) / m, n));
  printf("%.10lf", ans);
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000007;
char s[maxn];
int n, cnt, a[maxn];
bool check(int p, bool need_touch) {
  int x = 0, maxv = 0;
  bool touched = 0;
  for (int i = 1, _c = cnt; i <= _c; i++) {
    maxv = max(maxv, x);
    x += a[i];
    if (x <= p) {
      x = p + 1;
      touched = 1;
    }
  }
  return (x > maxv) && (!need_touch || touched);
}
int main() {
  cnt = 0;
  gets(s + 1);
  n = strlen(s + 1);
  int x = 1;
  while (x <= n) {
    int y = x;
    while (y < n && s[y + 1] == s[x]) ++y;
    a[++cnt] = y - x + 1;
    if (s[x] == 'L') a[cnt] *= -1;
    x = y + 1;
  }
  if (a[cnt] < 0)
    for (int i = 1, _c = cnt; i <= _c; i++) a[i] *= -1;
  if (check(-n - 1, 0)) {
    puts("1");
    return 0;
  }
  int res = 0;
  int l = -n, r = -1, mid, pos = 0;
  while (l <= r) {
    mid = (l + r) / 2;
    if (check(mid, 1)) {
      pos = mid;
      r = mid - 1;
    } else
      l = mid + 1;
  }
  res -= pos;
  printf("%d\n", res);
  return 0;
}

LRLRRL
```

Note that these are just random inputs and do not necessarily represent valid or interesting test cases.

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		Scanner in = new Scanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
	int n;
	char[] s;
	boolean checkValid(int lim) {
		int[] cnt = new int[n + n + 1];
		int cur = n;
		for(int i = 0; i < n + n + 1; ++ i) {
			cnt[i] = 0;
		}
		cnt[cur] = 1;
		for(int i = 0; i < n; ++ i) {
			if (s[i] == 'L' && cur - 1 != lim)
				-- cur;
			else if (s[i] == 'R' && cur + 1 != lim)
				++ cur;
			cnt[cur] ++;
		}
		return cnt[cur] == 1;
	}

    public void solve(int testNumber, Scanner in, PrintWriter out) {
		String str = in.next();
		s = str.toCharArray();
		n = s.length;
		if (checkValid(-1)) {
			out.println(1);
			return;
		}
		int l, r, mid;
		l = 0; r = n;
		for( ; l + 1 < r; ) {
			mid = l + r >> 1;
			if (checkValid(mid)) {
				r = mid;
			} else {
				l = mid;
			}
		}
		int ret = n - r;
		l = n; r = n + n;
		for( ; l + 1 < r; ) {
			mid = l + r >> 1;
			if (checkValid(mid)) {
				l = mid;
			} else {
				r = mid;
			}
		}
		ret += l - n;
		out.println(ret);
    }
}


def chk(x):
    d = (m - x) // (k - 1) * k
    if (m - x) % (k - 1):
        d += 1 + (m - x) % (k - 1)
    if d <= n - x:
        return True
    else:
        return False

def calc(e):
    if e == 1:
        return 2
    if e & 1:
        d = 2
    else:
        d = 1
    f = calc(e >> 1)
    d = d * f % D * f % D
    return d

n, m, k = map(int, input().split())
D = 1000000009

l = 0
h = n

while l < h:
    mid = l + h >>1
    if chk(mid):
        h = mid
    else:
        l = mid + 1

h = calc(l // k + 1) - 2
if h < 0:
    h += D

print((k * h % D + m - l // k * k) % D)

import java.io.InputStreamReader;
import static java.lang.Math.*;
import java.util.ArrayList;
import java.util.Scanner;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author pttrung
 */
public class C {

    public static long Mod = 1000000009;

    public static void main(String[] args) {
        Scanner in = new Scanner(new InputStreamReader(System.in));
        long n = in.nextInt();
        long m = in.nextInt();
        long k = in.nextInt();

        long X = Math.max(0, m - (n - n % k) / k * (k - 1) - n % k);
        //  System.out.println((n - n % k) / k * (k - 1));
        long result = (((pow(2, X + 1) - 2) + Mod) % Mod) * k;
        result += m - X * k;

        //  System.out.println(result % Mod);
        System.out.println(result % Mod);

    }

    static long pow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }

        long val = pow(a, b / 2);
        //System.out.println(val);
        if (b % 2 == 0) {
            return val * val % Mod;
        } else {
            return val * val * a % Mod;
        }
    }

    static void check(Point a, Point b, ArrayList<Point> p, Point[] rec, int index) {
        for (int i = 0; i < 4; i++) {
            int m = (i + index) % 4;
            int j = (i + 1 + index) % 4;
            Point k = intersect(minus(b, a), minus(rec[m], rec[j]), minus(rec[m], a));
            if (k.x >= 0 && k.x <= 1 && k.y >= 0 && k.y <= 1) {
                Point val = new Point(k.x * minus(b, a).x, k.x * minus(b, a).y);
                p.add(add(val, a));
                // System.out.println(a + " " + b + " " + rec[i] + " " + rec[j]);
                // System.out.println(add(val, a));
            }
        }
    }

    static Point intersect(Point a, Point b, Point c) {
        double D = cross(a, b);
        if (D != 0) {
            return new Point(cross(c, b) / D, cross(a, c) / D);
        }
        return null;
    }

    static Point convert(Point a, double angle) {
        double x = a.x * cos(angle) - a.y * sin(angle);
        double y = a.x * sin(angle) + a.y * cos(angle);
        return new Point(x, y);
    }

    static Point minus(Point a, Point b) {
        return new Point(a.x - b.x, a.y - b.y);
    }

    static Point add(Point a, Point b) {
        return new Point(a.x + b.x, a.y + b.y);
    }

    static double cross(Point a, Point b) {
        return a.x * b.y - a.y * b.x;
    }

    static class Point {

        double x, y;

        Point(double x, double y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "Point: " + x + " " + y;
        }
    }
}


b, p = map(int, input().split())
s1 = input()
s2 = input()

cnt = [0] * len(s2)
nxt = [0] * len(s2)

for i in range(len(s2)):
    pos = i
    for j in range(len(s1)):
        if s1[j] == s2[pos]:
            pos += 1
            if pos == len(s2):
                cnt[i] += 1
                pos = 0
    nxt[i] = pos

ans = 0
poss = 0
for i in range(b):
    ans += cnt[poss]
    poss = nxt[poss]

print(ans // p)

16 15 abcdefghijklmnopqr abcdefghijklmnopqrstuvwx

10000000 1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
z

32 31 abcdefghijklmnopqrstuvwxyyzaabcdef abcdefghijklmnopqrstuvwx

37 36 abcdefghijklmnopqrstuvwxyyzaabcdefghijk abcdefghijklmnopqrstuvwx

34 33 abcdefghijklmnopqrstuvwxyyzaabcdefgh abcdefghijklmnopqrstuvwx

20 19 abcdefghijklmnopqrstuv abcdefghijklmnopqrstuvwx

17 16 abcdefghijklmnopqrs abcdefghijklmnopqrstuvwx

27 26 abcdefghijklmnopqrstuvwxyyzaa abcdefghijklmnopqrstuvwx

15 14 abcdefghijklmnopq abcdefghijklmnopqrstuvwx

31 30 abcdefghijklmnopqrstuvwxyyzaabcde abcdefghijklmnopqrstuvwx

2308056 3
gabbfdehcegkmjicakkfhfahllalmkhhhjejfibdhgldjcbfmkfbmileigdmlhajfcciemfcbg
m

18 17 abcdefghijklmnopqrst abcdefghijklmnopqrstuvwx

11 10 abcdefghijklm abcdefghijklmnopqrstuvwx

35 34 abcdefghijklmnopqrstuvwxyyzaabcdefghi abcdefghijklmnopqrstuvwx

23 22 abcdefghijklmnopqrstuvwxy abcdefghijklmnopqrstuvwx

14 13 abcdefghijklmnop abcdefghijklmnopqrstuvwx

22 21 abcdefghijklmnopqrstuvwx abcdefghijklmnopqrstuvwx

25 24 abcdefghijklmnopqrstuvwxyyz abcdefghijklmnopqrstuvwx

28 27 abcdefghijklmnopqrstuvwxyyzaab abcdefghijklmnopqrstuvwx

21 20 abcdefghijklmnopqrstuvw abcdefghijklmnopqrstuvwx

38 37 abcdefghijklmnopqrstuvwxyyzaabcdefghijkl abcdefghijklmnopqrstuvwx

12 11 abcdefghijklmn abcdefghijklmnopqrstuvwx

19 18 abcdefghijklmnopqrstu abcdefghijklmnopqrstuvwx

36 35 abcdefghijklmnopqrstuvwxyyzaabcdefghij abcdefghijklmnopqrstuvwx

10 9 abcdefghijkl abcdefghijklmnopqrstuvwx

901 8
kikjbkgkkjeeficiigjjidfhkfdckjdkkbkfhkhdcjidjbfdfkbhbfjeiffkfgcaigck
gcjifhjjfedbfbdhickjbkkghfhbigkeff

13 12 abcdefghijklmno abcdefghijklmnopqrstuvwx

30 29 abcdefghijklmnopqrstuvwxyyzaabcd abcdefghijklmnopqrstuvwx

33 32 abcdefghijklmnopqrstuvwxyyzaabcdefg abcdefghijklmnopqrstuvwx

39 38 abcdefghijklmnopqrstuvwxyyzaabcdefghijklm abcdefghijklmnopqrstuvwx

29 28 abcdefghijklmnopqrstuvwxyyzaabc abcdefghijklmnopqrstuvwx

26 25 abcdefghijklmnopqrstuvwxyyza abcdefghijklmnopqrstuvwx

24 23 abcdefghijklmnopqrstuvwxyy abcdefghijklmnopqrstuvwx

#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
using namespace std;
const int maxn = 111;
int occ[maxn], en[maxn];
int main() {
  int b, d;
  scanf("%d %d", &b, &d);
  string a, c;
  cin >> a >> c;
  for (int e = 0; e < c.size(); e++) {
    int cur_c = e;
    int qtd = 0;
    for (int cur_a = 0; cur_a < a.size(); cur_a++) {
      if (a[cur_a] == c[cur_c]) {
        cur_c++;
      }
      if (cur_c == c.size()) {
        qtd++;
        cur_c = 0;
      }
    }
    occ[e] = qtd;
    en[e] = cur_c;
  }
  int tot = 0;
  int cur_c = 0;
  for (int e = 0; e < b; e++) {
    tot += occ[cur_c];
    cur_c = en[cur_c];
  }
  printf("%d\n", (tot / d));
  return 0;
}


n, k = map(int, input().split())

tab = [int(x) for x in input().split()]

i = 1
while k > 0:
    if tab[i - 1] < tab[i] - 1 and tab[i + 1] < tab[i] - 1:
        tab[i] -= 1
        k -= 1
    i += 2

print(' '.join(map(str, tab)))

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k, t;
  cin >> n >> k;
  int *a = new int[2 * n + 1];
  for (int i = 0; i < (int)2 * n + 1; i++) cin >> a[i];
  for (int i = 0; i < (int)2 * n + 1; i++) {
    if (!((i + 1) % 2)) {
      if (k && a[i] - a[i - 1] >= 2 && a[i] - a[i + 1] >= 2) {
        k--;
        a[i]--;
      }
    }
    cout << a[i] << " ";
  }
  cout << endl;
  return 0;
}


#include<iostream>
#include<stdio.h>
#include<cmath>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<queue>
#include<vector>
#include<map>
#define oo 0x3f3f3f3f
#define OO 0x3f3f3f3f3f3f3f3f
#define LL long long
#define res register int
#define STP system("pause")
using namespace std;
const int N=5e3;
LL f[N+5][N+5];
int a[N+5],b[N+5];
int main(){
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		scanf("%d",&a[i]);
		f[i][i]=0;
	}
	for(int i=1;i<=n;++i){
		scanf("%d",&b[i]);
	}
	LL ans=0;
	for(int k=2;k<=n;++k){
		for(int i=1;i<=n-k+1;++i){
			f[i][i+k-1]=f[i+1][i+k-2]+(LL)(a[i]-a[i+k-1])*(b[i]-b[i+k-1]);
			ans=min(ans,f[i][i+k-1]);
		}
	}
//	cout<<ans<<'\n';
//	STP;
	for(int i=1;i<=n;++i)
		ans-=(LL)a[i]*b[i];
	cout<<-ans<<'\n';
	return 0;
}

//package codeforces;
import java.util.*;
public class solution {
    public static void main(String args[]){
    	 Scanner s=new Scanner(System.in);
    	 int n=s.nextInt();
    	 long a[]=new long[n];
    	 long b[]=new long[n];
    	 for(int i=0;i<n;i++) {
    		 a[i]=s.nextInt();
    	 }
    	 for(int i=0;i<n;i++) {
    		 b[i]=s.nextInt();
    	 }
    	 long total=0;
    	 for(int i=0;i<n;i++) {
    		 total+=(a[i]*b[i]);
    	 }

    	 long ans=total;
    	 for(int i=0;i<n;i++) {
    		 long curr=total;
    		 for(int j=i-1,k=i+1;j>=0&& k<n;j--,k++) {
    			 curr=curr-(a[j]*b[j])-(a[k]*b[k])+(a[j]*b[k])+(a[k]*b[j]);
    			 ans=Math.max(ans,curr);
    		 }
    	 }
    	 for (int i = 0; i < n - 1; i++) {
    	        long curr = total;
    	        for (int j=i,k=i+1; j>= 0 && k<n;j--, k++) {
    	            curr -= a[j] * b[j] + a[k] * b[k];
    	            curr += a[j] * b[k] + a[k] * b[j];
    	            ans = Math.max(ans, curr);
    	        }
    	    }
    	 System.out.println(ans);
	     s.close();
    }
    static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;

public class C{

	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

	public static void main(String[] args)
	{
		OutputStream outputStream = System.out;
        FastReader sc = new FastReader();
        PrintWriter out = new PrintWriter(outputStream);

        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        int maxa = a/3;
        int maxb = b/2;
        int maxc = c/2;
        int maxw = Math.min(maxa, maxb);
        maxw = Math.min(maxw, maxc);
        long ans = (long)maxw*7;
        //out.println(ans);
        a = a-maxw*3;
        b = b-maxw*2;
        c = c-maxw*2;

        int ac = a;
        int bc = b;
        int cc = c;
        int max = 0;
        int cur = 0;
        char ch[] = {'f','r','c','f','c','r','f'};
        for(int i = 0; i < 7; i++)
        {
        	ac = a;
        	bc = b;
        	cc = c;
        	cur = 0;
        	for(int j = 0; j < 7; j++)
        	{
        		if(ch[(i+j)%7] == 'f')
        		{
        			ac--;
        		}
        		else if(ch[(i+j)%7] == 'r')
        		{
        			bc--;
        		}
        		else
        		{
        			cc--;
        		}
        		if(ac >= 0 && bc >= 0 && cc >= 0)
        		{
        			cur++;
        		}
        		else
        		{
        			break;
        		}
        	}
        	max = Math.max(max, cur);
        }
        ans += max;
        out.println(ans);
        out.close();
	}

}

import copy
nums = [0, 1, 2, 0, 2, 1, 0]
asdf = [3, 2, 2]
things = list(map(int, input().split(' ')))
max_idx = 0
for i in range(7):
    stuff = copy.deepcopy(things)
    idx = i
    while stuff[0] >= 0 and stuff[1] >= 0 and stuff[2] >= 0 and idx < 7:
        stuff[nums[idx % 7]] -= 1
        idx += 1
    num_weeks = min([stuff[0] // asdf[0],
                     stuff[1] // asdf[1],
                     stuff[2] // asdf[2]])
    stuff[0] -= asdf[0] * num_weeks
    stuff[1] -= asdf[1] * num_weeks
    stuff[2] -= asdf[2] * num_weeks
    idx += 7 * num_weeks
    while stuff[0] >= 0 and stuff[1] >= 0 and stuff[2] >= 0:
        stuff[nums[idx % 7]] -= 1
        idx += 1
    idx -= i
    if max_idx < idx:
        max_idx = idx
print(max_idx - 1)


#include <bits/stdc++.h>
using namespace std;
int n, m[100005], a[100005];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &a[i]);
    m[i] = a[i] + 1;
  }
  long long ans = 0;
  for (int i = n - 1; i >= 1; --i) m[i] = max(m[i], m[i + 1] - 1);
  for (int i = 1; i <= n; ++i) m[i] = max(m[i], m[i - 1]);
  for (int i = 1; i <= n; ++i) ans += (m[i] - a[i] - 1);
  cout << ans << endl;
  return 0;
}

import sys
n = int(input())
a = [int(x) for x in input().split(' ')]
maxm = 0
idx=0
ans=0
b=[0]*n
for i in range(n):
    if a[i]>=maxm:
        maxm=a[i]
        idx=i
for i in range(idx,n):
    b[i]=maxm+1
i=idx-1
while i>=0:
    b[i]=max(a[i]+1,b[i+1]-1)
    i-=1
for i in range(1,n):
    if b[i]<b[i-1]:
        b[i]=b[i-1]
    ans+=(b[i]-1-a[i])
print(ans)


def count_unic_mess(crt, display, array, n, result_arr):
    low_bound = 0 if crt - display < 0 else crt - display

    high_bound = n if crt + display + 1 > n else crt + display + 1

    result = high_bound - low_bound

    if array[crt] == 0:
        result_arr.append(result)
        return result

    ref = array[crt] - 1
    high_bound_ref = n if ref + display + 1 > n else ref + display + 1

    if high_bound_ref >= low_bound:
        result += result_arr[ref] - high_bound_ref + low_bound
    else:
        result += result_arr[ref]

    result_arr.append(result)
    return result

n, k = map(int, input().split(' '))

links = [int(x) for x in input().split(' ')]
count_arr = []

for i in range(n):
    print(count_unic_mess(i, k, links, n, count_arr), end=' ')

#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 100;
int ans[N], link[N];
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  for (int i = 1; i <= n; ++i) {
    int x;
    cin >> x;
    int down = max(1, i - k);
    int up = min(n, i + k);
    int down2 = max(1, x - k);
    int up2 = min(n, x + k);
    if (x == 0) {
      ans[i] = up - down + 1 + ans[x];
    } else {
      if (up2 < down)
        ans[i] = up - down + 1 + ans[x];
      else
        ans[i] = up - down + 1 + ans[x] - (up2 - down + 1);
    }
    cout << ans[i] << " ";
  }
  return 0;
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
        //String test = "A-large-practice";
        //ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + "-out.txt")));

        new Main(io).solve();
        io.close();
    }

    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    List<List<Integer>> gr = new ArrayList<>();
    long MOD = 1_000_000_007;

    int N, K;
    public void solve() {
        int[] c = new int[4];
        for(int i = 0;i<4;i++) {
            for (int j = 0; j < 4; j++) {
                int v = io.ri();
                c[i] |= v << j;
            }
        }
        for(int i = 0;i<4;i++){
            if(c[i] >> 3 > 0){
                if(c[i]!= 8){
                    io.writeLine("YES");
                    return;
                }
                for(int j = 1;j<4;j++){
                    int k = (i+j)%4;
                    if((c[k] & (1<<(j-1))) > 0){
                        io.writeLine("YES");
                        return;
                    }
                }
            }
        }

        io.writeLine("NO");
    }
}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
    public void flush(){this.out.flush();}
    public void close(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public void writeIntArray(int[] a, int k, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            if (i > 0) sb.append(separator);
            sb.append(a[i]);
        }
        this.writeLine(sb.toString());
    }
    public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
    public int[] readIntArray(int n) {
        int[] res = new int[n];
        char[] all = this.readLine().toCharArray();
        int cur = 0;boolean have = false;
        int k = 0;
        boolean neg = false;
        for(int i = 0;i<all.length;i++){
            if(all[i]>='0' && all[i]<='9'){
                cur = cur*10+all[i]-'0';
                have = true;
            }else if(all[i]=='-') {
                neg = true;
            }
            else if(have){
                res[k++] = neg?-cur:cur;
                cur = 0;
                have = false;
                neg = false;
            }
        }
        if(have)res[k++] = neg?-cur:cur;
        return res;
    }
    public int ri() {
        try {
            int r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public long readLong() {
        try {
            long r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public String readWord() {
        try {
            boolean start = false;
            StringBuilder sb = new StringBuilder();
            while (true) {
                int c = br.read();
                if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
                    sb.append((char)c);
                    start = true;
                } else if (start || c == -1) return sb.toString();
            }
        } catch (Exception ex) {
            return "";
        }
    }
    public char readSymbol() {
        try {
            while (true) {
                int c = br.read();
                if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
                    return (char) c;
                }
            }
        } catch (Exception ex) {
            return 0;
        }
    }
    //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
    public Pair(int a, int b) {this.a = a;this.b = b;}
    public int a;
    public int b;
}
class PairLL {
    public PairLL(long a, long b) {this.a = a;this.b = b;}
    public long a;
    public long b;
}
class Triple {
    public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
    public int a;
    public int b;
    public int c;
}

arr = [list() for i in range(4)]
arrp = []
for i in range(4):
    l, s, r, p = [int(i) for i in input().split()]
    arr[i].extend([l, s, r])
    arr[[3, i - 1][i > 0]].append(l)
    arr[[0, i + 1][i < 3]].append(r)
    arr[(i + 2) % 4].append(s)
    arrp.append(p)
for i in range(4):
    if arrp[i]:
        if 1 in arr[i]:
            print('YES')
            break
else:
    print('NO')


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Tifuera
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static
    @SuppressWarnings("Duplicates")
    class TaskE {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int haveCoins = in.nextInt();

            int[] toPay = new int[n];
            for (int i = 0; i < n; i++) {
                toPay[i] = in.nextInt();
            }

            int[] w = new int[n];
            for (int i = 0; i < n; i++) {
                w[i] = in.nextInt();
            }

            PriorityQueue<TaskE.DisSatisfaction> pq = new PriorityQueue<>();

            boolean[] isSatisfied = new boolean[n];

            long sumDis = 0;
            for (int i = 0; i < n; i++) {
                int curCoins = toPay[i] % 100;

                int ds = (100 - curCoins) % 100;
                if (ds > 0) {
                    pq.add(new TaskE.DisSatisfaction(ds * w[i], i));
                }

                if (haveCoins >= curCoins) {
                    haveCoins -= curCoins;
                    isSatisfied[i] = true;

                } else {
                    TaskE.DisSatisfaction disSatisfaction = pq.poll();
                    isSatisfied[i] = true;
                    isSatisfied[disSatisfaction.day] = false;

                    sumDis += disSatisfaction.value;

                    haveCoins -= curCoins;
                    haveCoins += 100;
                }
            }

            out.println(sumDis);
            for (int i = 0; i < n; i++) {
                if (isSatisfied[i]) {
                    out.print(toPay[i] / 100);
                    out.print(" ");
                    out.print(toPay[i] % 100);
                } else {
                    out.print((toPay[i] + 99) / 100);
                    out.print(" 0");
                }
                out.println();
            }

        }

        private static class DisSatisfaction implements Comparable<TaskE.DisSatisfaction> {
            private int value;
            private int day;

            public DisSatisfaction(int value, int day) {
                this.value = value;
                this.day = day;
            }

            public int compareTo(TaskE.DisSatisfaction o) {
                return Integer.compare(value, o.value);
            }

        }

    }

    static class InputReader {
        private BufferedReader reader;
        private String[] currentArray;
        private int curPointer;

        public InputReader(InputStream inputStream) {
            reader = new BufferedReader(new InputStreamReader(inputStream));
        }

        public int nextInt() {
            if ((currentArray == null) || (curPointer >= currentArray.length)) {
                try {
                    currentArray = reader.readLine().split(" ");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                curPointer = 0;
            }
            return Integer.parseInt(currentArray[curPointer++]);
        }

    }
}

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, m, c[N], w[N];
pair<int, int> ans[N];
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> c[i];
  for (int i = 0; i < n; i++) cin >> w[i];
  set<pair<int, int> > s;
  long long res = 0;
  for (int i = 0; i < n; i++) {
    int C = c[i] % 100, W = w[i];
    ans[i].first = c[i] / 100;
    ans[i].second = C;
    m -= C;
    if (C) s.insert(make_pair(W * (100 - C), i));
    while (m < 0) {
      pair<int, int> p = (*s.begin());
      s.erase(p);
      int idx = p.second;
      m += 100;
      res += p.first;
      ans[idx].second = 0;
      ans[idx].first++;
    }
  }
  cout << res << "\n";
  for (int i = 0; i < n; i++)
    cout << ans[i].first << " " << ans[i].second << "\n";
}


#include <bits/stdc++.h>
using namespace std;
long long getgcd(long long a, long long b) {
  long long t, sum;
  sum = a * b;
  while (b > 0) {
    t = b;
    b = a % b;
    a = t;
  }
  return sum / a;
}
int main() {
  long long n, a, b, p, q, sum1, sum2, sum3, x, y, ans;
  while (scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &p, &q) != EOF) {
    sum1 = n / a;
    sum2 = n / b;
    sum3 = n / getgcd(a, b);
    ans = (sum1 - sum3) * p + (sum2 - sum3) * q + sum3 * max(p, q);
    printf("%lld\n", ans);
  }
  return 0;
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class JotyandChocolate {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		String[] in = br.readLine().split(" ");
		long n = Long.parseLong(in[0]);
		long a = Long.parseLong(in[1]);
		long b = Long.parseLong(in[2]);
		long p = Long .parseLong(in[3]);
		long q  = Long.parseLong(in[4]);
		if(p<q){
			long lcm = a*b/gcd(a,b);
		    out.println((n/a-n/lcm)*p + (n/b)*q);
		}
		else{
			long lcm = a*b/gcd(a,b);
			out.println((n/a)*p + (n/b-n/lcm)*q);
		}
		out.flush();
		out.close();
	}

	private static long gcd(long a, long b){
		if(b==0)return a;
		else
			return gcd(b,a%b);

	}

}


def isPrime(n):
    if n==2:
        return True
    if n%2==0:
        return False
    for i in range(3,n,2):
        if i*i>n:
            break
        if n%i==0:
            return False
    return True
n=int(input())
if isPrime(n):
    print(1)
    print(n)
elif isPrime(n-2):
    print(2)
    print('2 '+str(n-2))
else:
    print(3)
    for i in range(2,n-3):
        if i>2 and i%2==0:
            continue
        if n-3-i<i:
            break
        if isPrime(i) and isPrime(n-3-i):
            print('3 '+str(i)+' '+str(n-3-i))
            break

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;

public class Main {
    Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        new D().doIt();
    }
    class D{
        ArrayList<Integer> array = new ArrayList<Integer>();
        int MAX = 1000000;
        boolean [] isprime = new boolean[MAX + 1];
        void eratos(){
            Arrays.fill(isprime, true);
            isprime[0] = false;
            isprime[1] = false;
            for(int i = 0; i * i <= MAX; i++){
                if(isprime[i]){
                    array.add(i);
                    for(int j = i * 2; j <= MAX; j+= i){
                        isprime[j] = false;
                    }
                }
            }
        }

        boolean is_prime(int n){
            int i = 2;
            while(i * i <= n){
                if(n % i == 0)return false;
                i += 1;
            }
            return true;
        }

        void doIt(){
            int n = sc.nextInt();
            eratos();
            if(is_prime(n)){
                System.out.println(1);
                System.out.println(n);
            }else{
                for(int i = 0;i < array.size();i++){
                    int n2 = n - array.get(i);
                    if(n2 < 2)break;
                    else if(is_prime(n2)){
                        System.out.println(2);
                        System.out.println(n2+" "+array.get(i));
                        System.exit(0);
                    }
                    for(int j = 0;j < array.size();j++){
                        int n3 = n2 - array.get(j);
                        if(n3 < 2)break;
                        else if(is_prime(n3)){
                            System.out.println(3);
                            System.out.println(n3+" "+array.get(i)+" "+array.get(j));
                            System.exit(0);
                        }
                    }
                }
            }
        }
    }
}


import java.util.*;
public class sd {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int[] h = new int[6];
        for(int i=0;i<6;i++){
            h[i] = in.nextInt();
        }
        int t=0,s=0;
        s = h[1] + h[2]-1;
        t = h[0] + h[3];
        int k = Math.min(h[0], h[3]);
        int p = 0,l=0;

            if(h[3]>=h[0]){
                for(int j=1;j<=Math.min(h[1], h[5]);j++){
                    t += 2*(k+j);
                    p = k+j;
                    s--;
                }
                for(int j=Math.min(h[1], h[5])+1;j<=Math.max(h[1], h[5]);j++){
                    t += 2*p;
                    s--;
                }

                while(s > 0){
                    p--;
                    t += 2*p;
                    s--;
                }

            }
            else{
                for(int j=1;j<=Math.min(h[2], h[4]);j++){
                    t += 2*(k+j);
                    p = k+j;
                    s--;

                }
                for(int j=Math.min(h[2], h[4])+1;j<=Math.max(h[2], h[4]);j++){
                    t += 2*(p);
                    s--;
                }
                while(s > 0){
                    p--;
                    t += 2*p;
                    s--;
                }

            }
            System.out.println(t);

    }

}


import java.util.Scanner;
/**
 * Created by kanghuang on 6/1/15.
 */
public class A {
    public static void main(String[] args){
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        if (n <= 2){
            System.out.print(1 + "\n" + 1);
        }
        else if (n == 3){
            System.out.print(2 + "\n" + 1 + " " + 3);
        }
        else if (n == 4){
            System.out.print(4 + "\n" +  "2 4 1 3");
        }
        else {
            System.out.println(n);
            for (int i = 1; i <= n; i += 2) {
                System.out.print(i + " ");
            }
            for (int i = 2; i <= n; i += 2) {
                System.out.print(i + " ");
            }
        }
    }

}

n = int(input())
if n ==1:
    print(1)
    print(1)
else:
    odd = [int(k) for k in range(n+1) if k % 2 != 0]
    odd.reverse()
    even =  [int(k) for k in range(1,n+1) if k % 2 == 0]
    even.reverse()
    odd_len = len(odd)
    #even.reverse()
    if abs(odd[odd_len-1]-even[0]) == 1:
        even = even[1:]
    num = odd + even
    print(len(num))
    num =[str(k) for k in num]
    print(" ".join(num))


song = input()
le = len(song)
su = 0
for x in range(1,le+1):
    su += 1/x
l = [0]*le
l[0] = su
diff = su
for x in range(1,int((le+1)/2)):
    diff -= (1/x + 1/(le+1-x))
    l[x] = l[x-1] + diff
for x in range(int((le+1)/2),le):
    l[x] = l[le-1-x]

ans = 0
for x in range(le):
    let = song[x]
    if let in ['A','E','I','O','U','Y']:
        ans += l[x]

print(ans)

Input: YI
KZTNJQLPZVHZKZWIB
Input: OU
Input: YB
Input: BY
Input: EI
Input: IE
IEAIAIO
Input: I
Input: BYOB
Input: YI
Input: YB
Input: YISVOWEL
Input: UUUU
Input: IO
EZYYOIYUZXEVRTOUYXIQ
Input: OY
Input: YI
YISVOWEL
Input: YYY
Input: A
Input: EEEEE
Input: IE
Input: IO
Input: IO
Input: Y
Input: BY
Input: U
Input: BE
Input: IEAIAIO
Input: OU
Input: O
Input: AI
Input: OY
Input: IO
MTOESEPRFEIWAIWLAFJMGBIQB
Input: E
Input: OU
Input: OY
Input: BY
Input: AAAAAA
Input: AI
A
Input: OU
Input: OY
Input: IA
Input: OOOO
Z
Input: YI
Input: BY
Input: YB
Input: YB
BYOB
Input: IIEEE
Input: EI
Input: AB

#include <bits/stdc++.h>
using namespace std;
string s;
long long int cnt[500005];
double avg = 0.0;
bool check(char c) {
  if (c == 'I' || c == 'E' || c == 'A' || c == 'O' || c == 'U' || c == 'Y')
    return true;
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> s;
  int n = int((s).length());
  s = "#" + s;
  for (int i = 1; i <= n; i++) {
    cnt[i] = cnt[i - 1];
    if (check(s[i])) cnt[i]++;
  }
  long long int cur = cnt[n];
  avg = 0.0;
  for (int m = int(1); m <= int(n); ++m) {
    avg += cur / (m + 0.0);
    if (m > n - m + 1) {
      cur -= cnt[m] - cnt[n - m];
    } else {
      cur += cnt[n - m] - cnt[m];
    }
  }
  printf("%.9f\n", avg);
  return 0;
}


n=int(input())
mat = []
mat.append('x'*(n+2))
for i in range(n):
    mat.append('x'+input()+'x')
mat.append('x'*(n+2))
output = "YES"
for i in range(1,n+1):
    if output == "NO":
        break
    for j in range(1,n+1):
        s=0
        if mat[i][j+1] == 'o':
            s+=1
        if mat[i][j-1] == 'o':
            s+=1
        if mat[i+1][j] == 'o':
            s+=1
        if mat[i-1][j] == 'o':
            s+=1
        if s%2:
            output = "NO"
            break
print(output)

33 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

38 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

35 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

21 x x x x x x x x x x x x x x x x x x x x o

28 x x x x x x x x x x x x x x x x x x x x x x x x x x x o

12
xxooxxoxxxoo
xxoooxoxoxoo
ooxoxoxxooxx
ooxxooooxoxo
xxxxxxxxoxxx
oxooooxxxooo
oxxoxoxoooxx
xxxxxxxooxox
oxoooooxoxxx
xxooxxoxxoxx
oxxxxxxxooxx
ooxoxooxxooo

32 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

19 x x x x x x x x x x x x x x x x x x o

36 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

24 x x x x x x x x x x x x x x x x x x x x x x x o

23 x x x x x x x x x x x x x x x x x x x x x x o

26 x x x x x x x x x x x x x x x x x x x x x x x x x o

29 x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

22 x x x x x x x x x x x x x x x x x x x x x o

43 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

39 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

10
xxxxxxxoox
xooxxooooo
oxoooxxooo
xoxxxxxxxx
xxoxooxxox
ooxoxxooox
ooxxxxxooo
xxxxoxooox
xoxxooxxxx
oooooxxoxo

20 x x x x x x x x x x x x x x x x x x x o

37 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

31 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

34 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

40 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

30 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

41 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x o

27 x x x x x x x x x x x x x x x x x x x x x x x x x x o

25 x x x x x x x x x x x x x x x x x x x x x x x x o

NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO NO YES NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;

public class Main
{

    public static void main(String args[]) throws IOException
    {
        final DataInputStream br = new DataInputStream(System.in);
        final PrintWriter bw = new PrintWriter(new BufferedOutputStream(System.out));
        Scanner scan = new Scanner(System.in);
        StringBuffer str = new StringBuffer();
        int t = ni(br);
        char ch[][] = new char[t][t];
        for (int i=0;i<t;i++)
        {

            for (int j=0;j<t;j++)
            {
                char cha = (char)br.read();
                if (cha == '\n' || cha == '\r')
                {
                    j--;
                    continue;
                }
                ch[i][j] = cha;
            }
        }

        int flag = 0;
        for (int i=0;i<t;i++)
        {
            int count = 0;
            for (int j=0;j<t;j++)
            {
                count += check(i+1,j,t,ch);
                count += check(i-1,j,t,ch);
                count += check(i,j+1,t,ch);
                count += check(i,j-1,t,ch);

                if (count % 2 != 0)
                {
                    flag = -1;
                    break;
                }
                count = 0;
            }
        }
        if (flag == -1)
            str.append("NO");
        else
            str.append("YES");

        System.out.println(str);

}
    static int check(int i,int j,int t,char[][] ch)
    {
        if (i >= t || i < 0 || j >= t || j < 0)
            return 0;
        else
        {
            if (ch[i][j] == 'o')
                return 1;
            else
                return 0;
        }
    }
    static int ni(DataInputStream br) throws IOException
    {

        int ret = 0;
        int x = br.read();
        while (x != -1 && (x < '0' || x > '9') && x != '-')
            x = br.read();
        ret = x - '0';
        x = br.read();
        while (x >= '0' && x <= '9' && x != -1 && x != ' ')
        {
            ret = (ret << 3) + (ret << 1) + x - '0';
            x = br.read();
        }
        return ret;
    }
}


import math
scann=input()
numbers=scann.split()
s=int(numbers[0])
s2=int(numbers[1])
min1=int(numbers[2])
max1=int(numbers[3])
total=int(numbers[4])
s2mp=int(numbers[5])
div=int(s2mp/s2)
mod=s2mp%s2
students=[]
for i in range(mod):
    students.append(div +1)  #intentarlo solo con piso
iter1=s2-mod
for j in range(iter1):
    students.append(div)
if(s!=s2):
    puntos_rest= total-s2mp;
    personas_rest=s-s2;
    restante=(int(puntos_rest/personas_rest)) # por si es impar
    mod_restante=(int(puntos_rest)% int(personas_rest)) # por si es impar
    for i in range(mod_restante):
        students.append(restante +1)  #intentarlo solo con piso
    aux=(s-s2)-mod_restante
    for j in range(aux):
        students.append(restante)

print(*students)

import java.util.Scanner;

public class Main {
    private static int n, k, l, r, sa, sk;
    private static Scanner entrada;

    public static void main(String[] args) {
        entrada = new Scanner(System.in);
        int values[];

        while (1 == 1) {
            try {

                int aux = 0, value;
                values = new int[1004];

                n = entrada.nextInt();
                k = entrada.nextInt();
                l = entrada.nextInt();
                r = entrada.nextInt();
                sa = entrada.nextInt();
                sk = entrada.nextInt();

                value = sk/k;

                for (int i = 0; i < sk - k*value; i++){
                    values[aux++] = value + 1;
                }

                for (int i = 0; i < k - (sk - k*value); i++){
                    values[aux++] = value;
                }

                if (n - k>0){
                    value = (sa - sk) / (n - k);
                    for (int i = 0; i < (sa - sk) - value*(n - k); i++){
                        values[aux++] = value + 1;
                    }
                    while (aux < n){
                        values[aux++] = value;
                    }
                }
                System.out.print(values[0]);
                for (int i = 1; i < n; i++) {
                    System.out.print(" "+ values[i]);
                }
                System.out.println();

            } catch (Exception e) {
                break;
            }

        }

    }

}


i = 0
t, sx, sy, ex, ey = list(map(int, input().split()))
second_string = input()
while i < t:
    if second_string[i] == 'E':
        if sx < ex: sx += 1
    elif second_string[i] == 'W':
        if sx > ex: sx -= 1
    elif second_string[i] == 'N':
        if sy < ey: sy += 1
    else:
        if sy > ey: sy -= 1
    i += 1
    if (sy == ey) and (sx == ex):
        print(i)
        break
    if i == t:
        print(-1)

37 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWN

42 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWNEWNE

35 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEE

41 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWNEWN

38 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWNE

36 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEW

41 -264908123 -86993764 -264908123 -86993723
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

39 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWNEE

40 0 0 1 1 ESESNWESNEWNEWNEWNEWNEWNEWNEWNEW

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        Reader.init(System.in);
        int d = Reader.nextInt() ;
        int x = Reader.nextInt() ;
        int y = Reader.nextInt() ;
        int xx = Reader.nextInt()-x ;
        int yy = Reader.nextInt()-y ;
        String a = Reader.next();
        int c = 0 , n = 0 , s = 0 , e = 0 , w = 0 ;
        if (xx>0) {
            e=xx;
        } else {
            w=Math.abs(xx) ;
        }
        if (yy>0) {
            n=yy ;
        } else {
            s=Math.abs(yy);
        }
        for (int i=0 ; i<a.length() ; i++) {
            if (a.charAt(i)=='S'&&s!=0) {
                c = i ;
                s -- ;
            }
            if (a.charAt(i)=='N'&&n!=0) {
                c = i ;
                n -- ;
            }
            if (a.charAt(i)=='W'&&w!=0) {
                c = i ;
                w -- ;
            }
            if (a.charAt(i)=='E'&&e!=0) {
                c = i ;
                e -- ;
            }
        }
        if (e!=0||s!=0||n!=0||w!=0) {
            System.out.println("-1");
        } else {
            System.out.println(c+1);
        }

    }

}
class Pair {
    int x ;
    int y ;

    Pair (int x , int y) {
        this.x = x ;
        this.y = y ;
    }
}
class Reader {

        static BufferedReader reader;
        static StringTokenizer tokenizer;

        public static int pars(String x) {
            int num = 0;
            int i = 0;
            if (x.charAt(0) == '-') {
                i = 1;
            }
            for (; i < x.length(); i++) {
                num = num * 10 + (x.charAt(i) - '0');
            }

            if (x.charAt(0) == '-') {
                return -num;
            }

            return num;
        }

        static void init(InputStream input) {
            reader = new BufferedReader(
                    new InputStreamReader(input));
            tokenizer = new StringTokenizer("");
        }

        static void init(FileReader input) {
            reader = new BufferedReader(input);
            tokenizer = new StringTokenizer("");
        }

        static String next() throws IOException {
            while (!tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(
                        reader.readLine());
            }
            return tokenizer.nextToken();
        }

        static int nextInt() throws IOException {
            return pars(next());
        }

        static long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        static double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }


#include <bits/stdc++.h>
using namespace std;
inline int read() {
  register int t = 0;
  register char v = getchar();
  while (v < '0') v = getchar();
  while (v >= '0') t = (t << 3) + (t << 1) + v - 48, v = getchar();
  return t;
}
int n, m, x, y;
double dp[1002][1002];
int main() {
  n = read(), m = read(), x = read(), y = read();
  for (register int i = n - 1; i >= x; --i)
    for (register int j = 1; j <= 50; ++j)
      if (m == 1)
        dp[i][1] = (dp[i][1] + dp[i + 1][1]) / 2.0 + 1;
      else {
        dp[i][1] = (dp[i][1] + dp[i + 1][1] + dp[i][2]) / 3.0 + 1;
        dp[i][m] = (dp[i][m] + dp[i][m - 1] + dp[i + 1][m]) / 3.0 + 1;
        for (register int k = 2; k < m; ++k)
          dp[i][k] =
              (dp[i][k] + dp[i][k - 1] + dp[i][k + 1] + dp[i + 1][k]) / 4.0 + 1;
      }
  printf("%.6lf", dp[x][y]);
}

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(in, out);
        out.close();
    }
}

class TaskD {
    public void solve(InputReader in, PrintWriter out) {
        double[][] dp = new double[1008][1008];
        int n = in.nextInt();
        int m = in.nextInt();
        int x = in.nextInt();
        int y = in.nextInt();

        if (m == 1) {
            out.printf("%.10f\n",(float) 2 * (n - x));
            return;
        }
        for (int i = 0; i < 1008; i++) {
            for (int j = 0; j < 1008; j++) {
                dp[i][j] = 0;
            }
        }
        for (int i = n - 1; i > 0; i--) {
            for(int t=0;t<60;t++) {
                for (int j = 1; j <= m; j++) {
                    if (j == 1) {
                        dp[i][j] = (dp[i][j + 1] + dp[i + 1][j] + dp[i][j]) / 3 + 1;
                    } else if (j == m) {
                        dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] + dp[i][j]) / 3 + 1;
                    } else {
                        dp[i][j] = (dp[i][j] + dp[i + 1][j] + dp[i][j + 1] + dp[i][j - 1]) / 4 + 1;
                    }
                }
            }
        }
        out.printf("%.10f\n", dp[x][y]);
    }
}

class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
}


import java.io.*;
import java.util.*;

public class Test {
	static BufferedReader reader;
	static StringTokenizer tokenizer;
	static PrintWriter writer;

	static int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	static long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	static double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	static String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

	public static void main(String[] args) throws IOException {
		reader = new BufferedReader(new InputStreamReader(System.in));
		tokenizer = null;
		writer = new PrintWriter(System.out);
		solve();
		reader.close();
		writer.close();
	}

	static long f(long n, long m) {
		if (n == 0)
			return 1;
		if (n % 2 == 1)
			return (f(n - 1, m) * 3) % m;
		else {
			long b = f(n / 2, m);
			return (b * b) % m;
		}
	}

	private static void solve() throws IOException {
		long n = nextInt();
		long m = nextInt();
		writer.println((f(n, m)+m - 1)%m);
	}
}

#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
long long n, m;
long long pp(long long t, long long p) {
  if (p == 0) return 1;
  if (p == 1) return t;
  long long res = pp(t, p / 2);
  res = (res * res) % m;
  if (p % 2) res = (res * t) % m;
  return res;
}
int main() {
  cin >> n >> m;
  long long p = pp(3, n);
  long long res = (p + m - 1) % m;
  cout << res << endl;
  return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define all(v) (v).begin(), (v).end()
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<LL, LL> pil;
const int MAX_N = 5005;
const LL MOD = 1000000007LL;
const int inf = 0x3fffffff;
int n;
bool chk[MAX_N];
pil arr[MAX_N];
LL get_dst(int u, int v){
	return (arr[u].fi - arr[v].fi) * (arr[u].fi - arr[v].fi)
			+ (arr[u].se - arr[v].se) * (arr[u].se - arr[v].se);
}
int get_far(int pre){
	int res = pre;
	for(int i=1;i<=n;i++){
		if(chk[i])	continue;
		if(get_dst(pre, res) < get_dst(pre, i))	res = i;
	}
	return res;
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%lld %lld",&arr[i].fi, &arr[i].se);
	}
	int pre = 1;
	chk[pre] = true;
	printf("%d ",pre);
	for(int i=2;i<=n;i++){
		int curr = get_far(pre);
		printf("%d ",curr);
		chk[pre = curr] = true;
	}
	printf("\n");
	return 0;
}

class Node:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getDist(self, a):
        dx = a.x - self.x
        dy = a.y - self.y
        return dx * dx + dy * dy

n = int(input())
a = []
for i in range(n):
    x, y = map(int, input().split())
    a.append(Node(x, y))

ans = [0]
vis = set()
vis.add(0)
while len(ans) < n:
    cur = ans[-1]
    maxDis = 0
    maxPos = 0
    for j in range(n):
        if cur == j or j in vis:
            continue
        val = a[cur].getDist(a[j])
        if val > maxDis:
            maxDis = val
            maxPos = j
    vis.add(maxPos)
    ans.append(maxPos)

for i in ans:
    print(i+1, end = ' ')
print()


from sys import stdin
import math
n=int(stdin.readline())
if n<3:
    k=n
else:
    d=0
    g=n
    for i in range(2,int(math.sqrt(n))+1):
        if n%i==0:
            d+=1
            g=math.gcd(g,i)
            if i*i!=n:
                d+=1
                g=math.gcd(g,n//i)
    if d==0:
        k=n
    else:
        k=g
print(k)

#include <bits/stdc++.h>
using namespace std;
int main() {
  long long N, n, a[1001], idx = 1, flag = 1;
  vector<long long> factors;
  scanf("%lld", &N);
  if (N < 4) {
    printf("%I64d\n", N);
    return 0;
  }
  n = N;
  if (n % 2 == 0) {
    factors.push_back(2);
    while (n % 2 == 0) {
      n /= 2;
    }
  }
  for (long long i = 3; i <= sqrt(N); i += 2) {
    if (n % i == 0) {
      factors.push_back(i);
      while (n % i == 0) {
        flag = 2;
        n /= i;
      }
    }
  }
  if (n > 2) {
    factors.push_back(n);
  }
  if (factors.size() == 1) {
    printf("%I64d\n", factors[0]);
  } else {
    if (N % 2 == 0) {
      if (factors.size() > 1) {
        printf("1\n");
      } else {
        printf("2\n");
      }
    } else {
      printf("1\n");
    }
  }
  return 0;
}