//package com.company;
//

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

public class Main {
    static int mod = 1000000007;
    public static void main(String[] args) throws IOException {
        MyScanner sc = new MyScanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        D.solve(sc, pw);
        pw.close();
    }

    public static class A {
        static int n, m;
        static long[] a;
        static long[] b;
        public static void solve(MyScanner sc, PrintWriter pw) throws IOException {
            n = sc.nextInt();
            m = sc.nextInt();
            a = new long[n]; b = new long[m];
            for (int i = 0; i < n; i++) {
                a[i] = sc.nextLong();
            }
            for (int i = 0; i < m; i++) {
                b[i] = sc.nextLong();
            }
            Arrays.sort(a);
            Arrays.sort(b);
            List<Long> res = new ArrayList<>();
            if (n == 2){
                if (a[0] * b[0] > a[1] * b[m - 1]) {
                    pw.println(Math.max(a[1] * b[0], a[1] * b[m - 1]));
                } else {
                    pw.println(Math.max(a[0] * b[0], a[0] * b[m - 1]));
                }
                return;
            }
            res.add(a[n-2] * b[0]);
            res.add(a[n-2] * b[m - 1]);
            res.add(a[1] * b[0]);
            res.add(a[1] * b[m - 1]);
            Collections.sort(res);
            pw.println(res.get(res.size() - 1));

        }
    }

    public static class B {
        static int[] lpp = new int[]{1, 0, 0, 0, 1, 0, 1, 0, 2, 1};
        public static void solve(MyScanner sc, PrintWriter pw) throws IOException {
            int k = sc.nextInt();
            if (k > 36) {
                pw.println(-1); return;
            }
            int n8 = k / 2;
            int n6 = k % 2;
            long res = 0;
            for (int i = 0; i < n8; i++) {
                res *= 10; res += 8;
            }
            for (int i = 0; i < n6; i++) {
                res *= 10; res += 6;
            }
            pw.println(res);

        }
    }

    public static class C {
        static int n;

        static int[] arr;
        static int[][][] dp;
        static int[] cnt1;
        static int[] cnt2;
        public static void solve(MyScanner sc, PrintWriter pw) throws IOException {
            n = sc.nextInt();
            arr = new int[n];
            dp = new int[n][n + 1][2];
            cnt1= new int[n + 1];
            cnt2 = new int[n + 1];
            for (int i = 0; i < n; i++) {
                arr[i] = sc.nextInt();
            }
            for (int i = n - 1; i >= 0; i--) {
                for (int j = i; j >= 0; j--) {
                    if (arr[j] == 1){
                        dp[i][j][0] = dp[i][j + 1][0] + 1;
                        dp[i][j][1] = dp[i][j + 1][1];
                    } else {
                        dp[i][j][0] = dp[i][j + 1][0];
                        dp[i][j][1] = Math.max(dp[i][j + 1][1] + 1, dp[i][j + 1][0] + 1);
                    }
                }
            }
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (arr[i] == 1) {
                    cnt++; cnt1[i + 1] = cnt;
                }
            }
            cnt = 0;
            for (int i = n - 1; i >=0; i--) {
                if (arr[i] == 2) {
                    cnt++;
                    cnt2[i] = cnt;
                }
            }
            cnt = 0;
            for (int i = 0; i < n; i++) {
                for (int j = i; j < n; j++) {
                    cnt = Math.max(cnt, cnt1[i] + Math.max(dp[j][i][1], dp[j][i][0]) + cnt2[j + 1]);
                }
            }
            pw.println(cnt);
        }
    }

    public static class D {
        static long p; static int k;
        public static void solve(MyScanner sc, PrintWriter pw) throws IOException {
            p = sc.nextLong();
            k = sc.nextInt();
            List<Long> coef = new ArrayList<>();
            long mv = p;
            while (true) {
                long b0 = -mv / k;
                if (b0 * k + mv < 0){
                    b0++;
                }
                coef.add(k * b0 + mv);
                if (0 <= b0 && b0 <= k) {
                    coef.add(b0); break;
                }
                if (coef.size() >= 1e6){
                    pw.println(-1); return;
                }
                mv = b0;
            }
            pw.println(coef.size());
            for (int i = 0; i < coef.size(); i++) {
                pw.print(coef.get(i) + " ");
            }
            pw.println();
        }

    }

    public static class E {
        static int n;
        static int[] x;
        static int[] y;
        static int[] r;
        public static double dist(int x1, int y1, double x2, double y2) {
            return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        }

        public static void solve(MyScanner sc, PrintWriter pw) throws IOException {
            n  = sc.nextInt();
            Random rnd = new Random();
            x = new int[n]; y = new int[n]; r = new int[n];
            for (int i = 0; i < n; i++) {
                x[i] = sc.nextInt();
                y[i] = sc.nextInt();
                r[i] = sc.nextInt();
            }
            int[] used = new int[100];
            for (int t = 0; t < n; t++) {
                for (int i = (x[t] - r[t]) * 100; i <= (x[t] + r[t]) * 100; i++) {
                    for (int j = (y[t] - r[t]) * 100; j <= (y[t] + r[t]) * 100; j++) {
                        int code = 0;
                        double x2 = (i + 0.0) / 100;
                        double y2 = (j + 0.0) / 100;
//                        x2 += rnd.nextDouble() / 10;
//                        y2 += rnd.nextDouble() / 10;
                        for (int k = 0; k < n; k++) {
                            double dis = dist(x[k], y[k], x2, y2);
                            if (dis + 1e-8 < r[k]) {
                                code += 1 << k;
                            }
                        }
                        used[code] = 1;
                    }
                }
            }

            int cnt = 0;
            for (int i = 0; i < 100; i++) {
                if (used[i] != 0) {
                    cnt ++;
                }
            }
            pw.println(cnt);
//            double arr[] = new double[21*21*21*21]; int idx = 0;
//            for (int i = -10; i <= 10; i++) {
//                for (int j = -10; j <= 10; j++) {
//                    for (int k = -10; k <= 10; k++) {
//                        for (int l = -10; l <= 10; l++) {
//                            double dit = dist(i, j, k, l);
//                            if (dit < 1e-8) continue;
//                            arr[idx++] = dit - (int) dit;
//                        }
//                    }
//                }
//            }
//            Arrays.sort(arr);
//            idx = 0;
//            while (arr[idx] < 1e-8){
//                idx++;
//            }
//            for (int i = idx; i < idx + 5; i++) {
//                pw.println(arr[i]);
//            }
        }
    }

    static class MyScanner {
        StringTokenizer st;
        BufferedReader br;

        public MyScanner(InputStream s){  br = new BufferedReader(new InputStreamReader(s));}

        public MyScanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);}

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

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

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

        public String nextLine() throws IOException {return br.readLine();}

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

        public boolean ready() throws IOException {return br.ready();}
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
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
 */
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);
        DeterminedCleanup solver = new DeterminedCleanup();
        solver.solve(1, in, out);
        out.close();
    }

    static class DeterminedCleanup {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long p = in.nextLong();
            long k = in.nextInt();
            int mx = 62;
            long[] coe = new long[mx];
            int d = (int) MathUtils.log(p, k) + 1;
            coe[0] = p % k;
            BigInteger[] pref = new BigInteger[mx];
            BigInteger kbig = new BigInteger(Long.toString(k));
            BigInteger pbig = new BigInteger(Long.toString(p));
            pref[0] = new BigInteger(Long.toString(coe[0]));
            for (int i = 1; i <= mx; i++) {
                if (kbig.pow(i).compareTo(pbig) <= 0) {
                    coe[i] = ((pbig.mod(kbig.pow(i + 1)).subtract(pref[i - 1])).divide(kbig.pow(i))).longValue();
                    pref[i] = kbig.pow(i).multiply(new BigInteger(Long.toString(coe[i]))).add(pref[i - 1]);
                } else {
                    d = i - 1;
                    break;
                }
            }
            for (int i = 1; i <= d; i += 2) {
                if (coe[i] > 0) {
                    coe[i] = -(k - coe[i]);
                    coe[i + 1]++;
                }
            }
            for (int i = 0; i <= d + 1; i++) {
                if (coe[i] == k) {
                    coe[i] = 0;
                    coe[i + 1]++;
                }
            }
            for (int i = mx - 1; i >= 0; i--) {
                if (coe[i] != 0) {
                    d = i;
                    break;
                }
            }
            out.println(d + 1);
            for (int i = 0; i <= d; i++) {
                out.println(Math.abs(coe[i]));
            }
        }

    }

    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());
        }

    }

    static class MathUtils {
        public static double log(double val, double base) {
            return Math.log(val) / Math.log(base);
        }

    }
}


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class D {
    private static class BufferedScanner {
        BufferedReader mReader;
        StringTokenizer mTokenizer;

        BufferedScanner(InputStream inputStream) {
            mReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        String next() {
            while (mTokenizer == null || !mTokenizer.hasMoreElements()) {
                String line = readLine();
                if (line != null) {
                    mTokenizer = new StringTokenizer(line);
                } else {
                    break;
                }
            }
            return mTokenizer != null ? mTokenizer.nextToken() : null;
        }

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

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

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

        String nextLine() {
            return readLine();
        }

        private String readLine() {
            try {
                return mReader.readLine();
            } catch (IOException ignore) {
                return null;
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new D().solve();
    }

    private BufferedScanner mReader;
    private PrintStream mWriter;

    private D() throws IOException {
        InputStream actualInputStream;
        if (System.getProperty("ONLINE_JUDGE") != null) {
            actualInputStream = System.in;
        } else {
            File inputFile = new File("in.txt");
            if (!inputFile.exists()) {
                //noinspection ResultOfMethodCallIgnored
                inputFile.createNewFile();
                throw new FileNotFoundException("File wasn't found, but now is created");
            }
            actualInputStream = new FileInputStream(inputFile);
        }
        mReader = new BufferedScanner(new BufferedInputStream(actualInputStream));
        mWriter = System.out;
    }

    private void solve() throws IOException {
        long p = mReader.nextInt();
        long k = mReader.nextInt();
//
        List<Long> coefs = new ArrayList<>();

        long f = p % k;
        long q = p / (-k);

        coefs.add(f);

        while (q != 0) {
            f = (q % k + k) % k;
            q -= (q % k + k) % k;
            q /= -k;

            coefs.add(f);
        }

        System.out.println(coefs.size());
        for (Long coef : coefs) {
            System.out.println(coef);
        }
    }
}


import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner scanner=new Scanner(System.in);

        long p=scanner.nextInt();
        int k=scanner.nextInt();

        ArrayList<Long> list=new ArrayList<>();
        for (int i=0;p>0;i++) {
            list.add((i%2==0?1:-1)*(p%k));
            p/=k;
        }

        for (int i=0;i<list.size();i++) {
            if (list.get(i)<0) {
                list.set(i, list.get(i)+k);
                if (i==list.size()-1) list.add(1L);
                else list.set(i+1, list.get(i+1)+1);
            }
            else if (list.get(i)>=k) {
                list.set(i, list.get(i)-k);
                if (i==list.size()-1) list.add(-1L);
                else list.set(i+1, list.get(i+1)-1);
            }
        }
        System.out.println(list.size());
        System.out.println(String.join(" ", list.stream().map(String::valueOf).collect(Collectors.toList())));
    }

}


import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int row = in.nextInt();
        int col = in.nextInt();
        in.nextLine();
        char[][] foods = new char[row][col];
        for (int i = 0; i < row; i++) {
            String line = in.nextLine();
            // System.out.println(line);
            for (int j = 0; j < col; j++) {
                foods[i][j] = line.charAt(j);
            }
        }

        int i = 0;
        int j = 0;
        int res = 0;
        while (true) {
            if (foods[i][j] == '*') {
                res++;
                // System.out.println("i " + i + ", j " + j);

            }
            if (i == row - 1 && j == col - 1) {
                System.out.println(res);
                return;
            }
            if (j == col - 1 || foods[i + 1][j] == '*') {
                i++;
                continue;
            }
            j++;
        }
    }
}


import java.io.*;
import java.util.*;
public class codeforcesE1{
	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());
		}
		float nextFloat(){
			return Float.parseFloat(next());
		}
	}
	public static void main(String args[]){
		FastReader fs=new FastReader();
		int i=0,j=0;
		int h=fs.nextInt();
		int w=fs.nextInt();
		char[][] mat=new char[h][w];
		for(i=0;i<h;i++){
			String s=fs.next();
			for(j=0;j<w;j++){
				mat[i][j]=s.charAt(j);
			}
		}
		int cnt=0;
		for(i=0;i<h;i++){
			for(j=0;j<w;j++){
				if(mat[i][j]=='*'){
					cnt++;
					break;
				}
			}
			if(mat[i][j]=='*')
				break;
		}
		if(i==h-1 && j==w-1){
			System.out.println(1);
		}
		else{
		while(i!=h-1 && j!=w-1){
			i++;
			if(i!=h-1){
				for(int k=j;k<w;k++){
					if(mat[i][k]=='*'){
						j=k;
						cnt++;
						break;
					}
				}
			}
			if(i==h-1){
				for(int k=j;k<w;k++){
					j=k;
					if(mat[i][j]=='*'){
						cnt++;
					}
				}
			}
		}
		System.out.println(cnt);
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            ECakewalk solver = new ECakewalk();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class ECakewalk {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.ri();
            int m = in.ri();
            char[][] mat = new char[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    mat[i][j] = in.rc();
                }
            }
            int x = 0;
            int y = 0;
            int ans = mat[0][0] == '*' ? 1 : 0;
            while (true) {
                if (y == m - 1 || x + 1 < n && mat[x + 1][y] == '*') {
                    x++;
                } else {
                    y++;
                }
                ans += mat[x][y] == '*' ? 1 : 0;
                if (x == n - 1 && y == m - 1) {
                    break;
                }
            }
            out.println(ans);
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int ri() {
            return readInt();
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public char rc() {
            return readChar();
        }

        public char readChar() {
            skipBlank();
            char c = (char) next;
            next = read();
            return c;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private static final int THRESHOLD = 32 << 10;
        private final Writer os;
        private StringBuilder cache = new StringBuilder(THRESHOLD * 2);

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        private void afterWrite() {
            if (cache.length() < THRESHOLD) {
                return;
            }
            flush();
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            afterWrite();
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            afterWrite();
            return this;
        }

        public FastOutput println(int c) {
            return append(c).println();
        }

        public FastOutput println() {
            return append('\n');
        }

        public FastOutput flush() {
            try {
//            boolean success = false;
//            if (stringBuilderValueField != null) {
//                try {
//                    char[] value = (char[]) stringBuilderValueField.get(cache);
//                    os.write(value, 0, cache.length());
//                    success = true;
//                } catch (Exception e) {
//                }
//            }
//            if (!success) {
                os.append(cache);
//            }
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
}


import java.util.LinkedList;
import java.util.Scanner;

public class IsItRated2 {

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

        int alto = entrada.nextInt();
        int ancho = entrada.nextInt();
        entrada.nextLine();

        boolean [][] matrix = new boolean [alto][ancho];

        for (int i = 0; i < alto; i++){
            char [] read = entrada.nextLine().strip().toCharArray();
            for (int j = 0; j < ancho; j++){
                matrix[i][j] = read[j] == '*';
            }
        }

        int berries = 0;

        if (matrix[0][0]) berries++;

        int mouseX = 0, mouseY = 0;

        int [] goal = findNearest(matrix, mouseX, mouseY);

        while (true){
            if (mouseX == goal[0] && mouseY == goal[1]){
                berries++;
                goal = findNearest(matrix, mouseX, mouseY);
            } else if (mouseY < goal[1]){
                mouseY++;
            } else if (mouseX < goal[0]){
                mouseX++;
            } else {
                System.out.println(berries);
                return;
            }
        }

    }

    public static int [] findNearest (boolean [][] matrix, int x, int y){
        LinkedList <Integer []> queue = new LinkedList<>();
        Integer [] position = {x, y+1};
        queue.add(position);
        Integer [] position2 = {x+1, y};
        queue.add(position2);
        while (!queue.isEmpty()){
            Integer [] pointer = queue.pop();
            int pointX = pointer[0];
            int pointY = pointer[1];
            if (pointX >= matrix.length || pointY >= matrix[0].length) continue;
            if (matrix[pointX][pointY]) {
                return new int [] {pointX, pointY};
            }
            queue.add(new Integer [] {pointX, pointY+1});
            queue.add(new Integer [] {pointX+1, pointY});
        }
        int [] nulo = {-1, -1};
        return nulo;

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class D2 {
    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 FastReader scn = new FastReader();

    // type 0 knight 1 bishop 2 rook
    private static class node implements Comparable<node>{
        int x;
        int y;
        int val;
        int steps;
        int rep;
        int type;

        public node(int x,int y,int val, int st,int rep, int typ){
            this.x = x;
            this.y = y;
            this.rep = rep;
            this.val = val;
            this.steps = st;
            this.type = typ;
        }

        @Override
        public int compareTo(node other){
            if(this.steps == other.steps) return this.rep - other.rep;
            return this.steps - other.steps;
        }
    }

    public static void main(String[] args) {
        int n = scn.nextInt();
        int[][] pos = new int[n*n +1][2] ;
        for(int i = 0; i<n; i++){
            for(int j = 0; j<n; j++){
                pos[scn.nextInt()] = new int[]{i,j};
            }
        }

        PriorityQueue<node> Queue = new PriorityQueue<>();
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,0));
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,1));
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,2));

        int[][][] move = new int[3][][];
        move[0] = new int[][]{{-2,-1},{-1,-2},{2,-1},{1,-2},{-2,1},{-1,2},{2,1},{1,2}};
        move[1] = new int[][]{{-1,-1},{-1,1},{1,-1},{1,1}};
        move[2] = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};

        boolean[][][][] visited = new boolean[n][n][n*n +1][3]; // x,y,value,type

        while(!Queue.isEmpty()){
            node s = Queue.poll();
            if(s.x<0 || s.y<0 || s.x >=n || s.y >=n) continue;
            if(visited[s.x][s.y][s.val][s.type]) continue;
            visited[s.x][s.y][s.val][s.type] = true;
            if(pos[s.val+1][0] == s.x && pos[s.val+1][1] == s.y){
                s.val++;
                if(s.val == n*n){
                    System.out.println(s.steps + " " + s.rep);
                    break;
                }
                visited[s.x][s.y][s.val][s.type] = true;
            }

            for(int i = 0; i< 3; i++) Queue.add(new node(s.x,s.y,s.val,s.steps+1,s.rep+1,i));

            for(int[] m : move[s.type]){
                if(s.type == 0){
                    for(int j = 0; j<m.length ; j++) Queue.add(new node(s.x + m[0], s.y + m[1], s.val , s.steps+1, s.rep , s.type));
                }else{
                    for(int j = 1; j<=n; j++) Queue.add(new node(s.x + j*m[0], s.y + j*m[1], s.val , s.steps+1, s.rep , s.type));
                }
            }
        }
    }
}


/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking interest
*******************************
I'm standing on top of my Monopoly board
That means I'm on top of my game and it don't stop
til my hip don't hop anymore
https://www.a2oj.com/Ladder16.html
*******************************
Shining through the city with a little funk and soul
*******************************
300iq as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;

   public class x1065D
   {
      public static void main(String hi[]) throws Exception
      {
         BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
         StringTokenizer st = new StringTokenizer(infile.readLine());
         int N = Integer.parseInt(st.nextToken());
         int[][] grid = new int[N][N];
         for(int i=0; i < N; i++)
         {
            st = new StringTokenizer(infile.readLine());
            for(int a=0; a < N; a++)
               grid[i][a] = Integer.parseInt(st.nextToken());
         }
         int[] loc = new int[N*N+1];
         for(int r=0; r < N; r++)
            for(int c=0; c < N; c++)
               loc[grid[r][c]] = r*N+c;
         //knight bishop rook
         int[][][] dist = new int[N*N+1][3][N*N+1];
         int[][][] replace = new int[N*N+1][3][N*N+1];
         for(int i=0; i <= N*N; i++)
            for(int p=0; p < 3; p++)
            {
               Arrays.fill(dist[i][p], 420420420);
               Arrays.fill(replace[i][p], 420420420);
            }
         int start = loc[1];
         for(int p=0; p < 3; p++)
            dist[start][p][1] = replace[start][p][1] = 0;
         ArrayDeque<Integer> q = new ArrayDeque<Integer>();
         for(int p=0; p < 3; p++)
         {
            q.add(start);
            q.add(p);
            q.add(1);
         }
         while(q.size() > 0)
         {
            int tempo = q.poll();
            int piece = q.poll();
            int target = q.poll();
            int x = tempo/N;
            int y = tempo%N;
            //swap
            for(int p=0; p < 3; p++)
            {
               if(piece == p)
                  continue;
               if(replace[tempo][p][target] > replace[tempo][piece][target]+1 && dist[tempo][p][target] == dist[tempo][piece][target]+1)
               {
                  replace[tempo][p][target] = replace[tempo][piece][target]+1;
                  q.add(tempo);
                  q.add(p);
                  q.add(target);
               }
               else if(dist[tempo][p][target] > dist[tempo][piece][target]+1)
               {
                  replace[tempo][p][target] = replace[tempo][piece][target]+1;
                  dist[tempo][p][target] = dist[tempo][piece][target]+1;
                  q.add(tempo);
                  q.add(p);
                  q.add(target);
               }
            }
            //move
            if(piece == 0)
            {
               for(int dx=-2; dx <= 2; dx++)
                  for(int dy=-2; dy <= 2; dy++)
                  {
                     if(dx == 0 || dy == 0 || Math.abs(dx) == Math.abs(dy))
                        continue;
                     int r = x+dx;
                     int c = y+dy;
                     if(Math.min(r,c) < 0 || Math.max(r,c) >= N)
                        continue;
                     int id = target+(grid[r][c]-1 == target ? 1 : 0);
                     if(dist[r*N+c][piece][id] > dist[tempo][piece][target]+1)
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        dist[r*N+c][piece][id] = dist[tempo][piece][target]+1;
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                     else if(dist[r*N+c][piece][id] == dist[tempo][piece][target]+1 && replace[r*N+c][piece][id] > replace[tempo][piece][target])
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                  }
            }
            else if(piece == 1)
            {
               for(int a=1; a < N; a++)
                  for(int dx=-1; dx <= 1; dx+=2)
                     for(int dy=-1; dy <= 1; dy+=2)
                     {
                        int r = x+dx*a;
                        int c = y+dy*a;
                        if(Math.min(r,c) < 0 || Math.max(r,c) >= N)
                           continue;
                        int id = target+(grid[r][c]-1 == target ? 1 : 0);
                        if(dist[r*N+c][piece][id] > dist[tempo][piece][target]+1)
                        {
                           replace[r*N+c][piece][id] = replace[tempo][piece][target];
                           dist[r*N+c][piece][id] = dist[tempo][piece][target]+1;
                           q.add(r*N+c);
                           q.add(piece);
                           q.add(id);
                        }
                        else if(dist[r*N+c][piece][id] == dist[tempo][piece][target]+1 && replace[r*N+c][piece][id] > replace[tempo][piece][target])
                        {
                           replace[r*N+c][piece][id] = replace[tempo][piece][target];
                           q.add(r*N+c);
                           q.add(piece);
                           q.add(id);
                        }
                     }
            }
            else
            {
               for(int a=1; a < N; a++)
                  for(int dx=-1; dx <= 1; dx+=2)
                  {
                     int r = x+dx*a;
                     int c = y;
                     if(Math.min(r,c) < 0 || Math.max(r,c) >= N)
                        continue;
                     int id = target+(grid[r][c]-1 == target ? 1 : 0);
                     if(dist[r*N+c][piece][id] > dist[tempo][piece][target]+1)
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        dist[r*N+c][piece][id] = dist[tempo][piece][target]+1;
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                     else if(dist[r*N+c][piece][id] == dist[tempo][piece][target]+1 && replace[r*N+c][piece][id] > replace[tempo][piece][target])
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                  }
               for(int a=1; a < N; a++)
                  for(int dy=-1; dy <= 1; dy+=2)
                  {
                     int r = x;
                     int c = y+dy*a;
                     if(Math.min(r,c) < 0 || Math.max(r,c) >= N)
                        continue;
                     int id = target+(grid[r][c]-1 == target ? 1 : 0);
                     if(dist[r*N+c][piece][id] > dist[tempo][piece][target]+1)
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        dist[r*N+c][piece][id] = dist[tempo][piece][target]+1;
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                     else if(dist[r*N+c][piece][id] == dist[tempo][piece][target]+1 && replace[r*N+c][piece][id] > replace[tempo][piece][target])
                     {
                        replace[r*N+c][piece][id] = replace[tempo][piece][target];
                        q.add(r*N+c);
                        q.add(piece);
                        q.add(id);
                     }
                  }
            }
         }
         int minDist = 420420420;
         int minRep = 420420420;
         int lmao = N*N;
         for(int p=0; p < 3; p++)
         {
            if(minDist > dist[loc[lmao]][p][lmao])
            {
               minDist = dist[loc[lmao]][p][lmao];
               minRep = replace[loc[lmao]][p][lmao];
            }
            else if(minDist == dist[loc[lmao]][p][lmao] && minRep > replace[loc[lmao]][p][lmao])
               minRep = replace[loc[lmao]][p][lmao];
         }
         System.out.println(minDist+" "+minRep);
      }
   }


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class D2 {
    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 FastReader scn = new FastReader();

    // type 0 knight 1 bishop 2 rook
    private static class node implements Comparable<node>{
        int x;
        int y;
        int val;
        int steps;
        int rep;
        int type;

        public node(int x,int y,int val, int st,int rep, int typ){
            this.x = x;
            this.y = y;
            this.rep = rep;
            this.val = val;
            this.steps = st;
            this.type = typ;
        }

        @Override
        public int compareTo(node other){
            if(this.steps == other.steps) return this.rep - other.rep;
            return this.steps - other.steps;
        }
    }

    public static void main(String[] args) {
        int n = scn.nextInt();
        int[][] pos = new int[n*n +1][2] ;
        for(int i = 0; i<n; i++){
            for(int j = 0; j<n; j++){
                pos[scn.nextInt()] = new int[]{i,j};
            }
        }

        PriorityQueue<node> Queue = new PriorityQueue<>();
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,0));
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,1));
        Queue.add(new node(pos[1][0],pos[1][1],1,0,0,2));

        int[][][] move = new int[3][][];
        move[0] = new int[][]{{-2,-1},{-1,-2},{2,-1},{1,-2},{-2,1},{-1,2},{2,1},{1,2}};
        move[1] = new int[][]{{-1,-1},{-1,1},{1,-1},{1,1}};
        move[2] = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};

        boolean[][][][] visited = new boolean[n][n][n*n +1][3]; // x,y,value,type

        while(!Queue.isEmpty()){
            node s = Queue.poll();
            if(s.x<0 || s.y<0 || s.x >=n || s.y >=n) continue;
            if(visited[s.x][s.y][s.val][s.type]) continue;
            visited[s.x][s.y][s.val][s.type] = true;
            if(pos[s.val+1][0] == s.x && pos[s.val+1][1] == s.y){
                s.val++;
                if(s.val == n*n){
                    System.out.println(s.steps + " " + s.rep);
                    break;
                }
                visited[s.x][s.y][s.val][s.type] = true;
            }

            for(int i = 0; i< 3; i++) Queue.add(new node(s.x,s.y,s.val,s.steps+1,s.rep+1,i));

            for(int[] m : move[s.type]){
                if(s.type == 0){
                    Queue.add(new node(s.x + m[0], s.y + m[1], s.val , s.steps+1, s.rep , s.type));
                }else{
                    for(int j = 1; j<=n; j++) Queue.add(new node(s.x + j*m[0], s.y + j*m[1], s.val , s.steps+1, s.rep , s.type));
                }
            }
        }
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

public class d{

	static class Pos{
		int i,j;
		Pos(int i, int j){this.i=i;this.j=j;}
	}
	static class Node{
		int i,j,k,l,c;
		Node(int i,int j,int k,int l,int c){this.i=i;this.j=j;this.k=k;this.l=l;this.c=c;}
	}

	static void solve(){
		int n = ni();
		int[][][][] dis = new int[n][n][3][n*n+1];
		Pos[] pos =new Pos[n*n];
		for(int i=0;i<n;++i)for(int j=0;j<n;++j)pos[ni()-1] = new Pos(i, j);
		for(int i=0;i<n;++i)for(int j=0;j<n;++j)for(int k=0;k<3;++k)for(int l=0;l<=n*n;++l)dis[i][j][k][l]=Integer.MAX_VALUE;
		PriorityQueue<Node> que = new PriorityQueue<>((a,b)->a.c-b.c);
		for(int k=0;k<3;++k){
			dis[pos[0].i][pos[0].j][k][1]=0;
			que.add(new Node(pos[0].i, pos[0].j, k, 1, 0));
		}
		List<Integer> movex[] = new List[3];
		List<Integer> movey[] = new List[3];
		movex[0] = Arrays.asList(-2,-2,-1,-1,1,1,2,2);
		movey[0] = Arrays.asList(1,-1,2,-2,2,-2,1,-1);
		for(int i=1;i<3;++i){
			movex[i]=new ArrayList<>();
			movey[i]=new ArrayList<>();
		}
		for(int i=1;i<=n;++i){
			movex[1].add(i);movex[1].add(-i);
			movey[1].add(0);movey[1].add(0);
			movex[1].add(0);movex[1].add(0);
			movey[1].add(i);movey[1].add(-i);

			movex[2].add(i);movex[2].add(-i);
			movey[2].add(i);movey[2].add(-i);
			movex[2].add(i);movex[2].add(-i);
			movey[2].add(-i);movey[2].add(i);
		}
		while(!que.isEmpty()){
			Node node = que.poll();
			if(node.c > dis[node.i][node.j][node.k][node.l])continue;
			int i=node.i, j=node.j, k=node.k, l=node.l;
			if(l==n*n){
				out.println(node.c/1000+" "+node.c%1000);
				return;
			}
			for(int kk=0;kk<3;++kk){
				if(kk==k)continue;
				if(dis[i][j][kk][l] > dis[i][j][k][l]+1001){
					dis[i][j][kk][l]=dis[i][j][k][l]+1001;
					que.add(new Node(i, j, kk, l, dis[i][j][kk][l]));
				}
			}
			for(int x=0;x<movex[k].size();++x){
				int dx = movex[k].get(x);
				int dy = movey[k].get(x);

				if(inrange(i+dy, j+dx, n, n)){
					int ll = l;
					if(pos[l].i==i+dy && pos[l].j==j+dx)++ll;
					if(dis[i+dy][j+dx][k][ll]>dis[i][j][k][l]+1000){
						dis[i+dy][j+dx][k][ll]=dis[i][j][k][l]+1000;
						que.add(new Node(i+dy, j+dx, k, ll, dis[i+dy][j+dx][k][ll]));
					}
				}
			}
		}

	}

	 public static void main(String[] args){
		 solve();
		 out.flush();
	 }
	 private static InputStream in = System.in;
	 private static PrintWriter out = new PrintWriter(System.out);

	 static boolean inrange(int y, int x, int h, int w){
		 return y>=0 && y<h && x>=0 && x<w;
	 }
	 @SuppressWarnings("unchecked")
	 static<T extends Comparable> int lower_bound(List<T> list, T key){
		 int lower=-1;int upper=list.size();
		 while(upper - lower>1){
		 int center =(upper+lower)/2;
		 if(list.get(center).compareTo(key)>=0)upper=center;
		 else lower=center;
		 }
		 return upper;
	 }
	 @SuppressWarnings("unchecked")
	 static <T extends Comparable> int upper_bound(List<T> list, T key){
		 int lower=-1;int upper=list.size();
		 while(upper-lower >1){
		 int center=(upper+lower)/2;
		 if(list.get(center).compareTo(key)>0)upper=center;
		 else lower=center;
		 }
		 return upper;
	 }
	 @SuppressWarnings("unchecked")
	 static <T extends Comparable> boolean next_permutation(List<T> list){
		 int lastIndex = list.size()-2;
		 while(lastIndex>=0 && list.get(lastIndex).compareTo(list.get(lastIndex+1))>=0)--lastIndex;
		 if(lastIndex<0)return false;
		 int swapIndex = list.size()-1;
		 while(list.get(lastIndex).compareTo(list.get(swapIndex))>=0)swapIndex--;
		 T tmp = list.get(lastIndex);
		 list.set(lastIndex++, list.get(swapIndex));
		 list.set(swapIndex, tmp);
		 swapIndex = list.size()-1;
		 while(lastIndex<swapIndex){
		 tmp = list.get(lastIndex);
		 list.set(lastIndex, list.get(swapIndex));
		 list.set(swapIndex, tmp);
		 ++lastIndex;--swapIndex;
		 }
		 return true;
	 }
	 private static final byte[] buffer = new byte[1<<15];
	 private static int ptr = 0;
	 private static int buflen = 0;
	 private static boolean hasNextByte(){
		 if(ptr<buflen)return true;
		 ptr = 0;
		 try{
			 buflen = in.read(buffer);
		 } catch (IOException e){
			 e.printStackTrace();
		 }
		 return buflen>0;
	 }
	 private static int readByte(){ if(hasNextByte()) return buffer[ptr++]; else return -1;}
	 private static boolean isSpaceChar(int c){ return !(33<=c && c<=126);}
	 private static int skip(){int res; while((res=readByte())!=-1 && isSpaceChar(res)); return res;}

	 private static double nd(){ return Double.parseDouble(ns()); }
	 private static char nc(){ return (char)skip(); }
	 private static String ns(){
		 StringBuilder sb = new StringBuilder();
		 for(int b=skip();!isSpaceChar(b);b=readByte())sb.append((char)b);
		 return sb.toString();
	 }
	 private static int[] nia(int n){
		 int[] res = new int[n];
		 for(int i=0;i<n;++i)res[i]=ni();
		 return res;
	 }
	 private static long[] nla(int n){
		 long[] res = new long[n];
		 for(int i=0;i<n;++i)res[i]=nl();
		 return res;
	 }
	 private static int ni(){
		 int res=0,b;
		 boolean minus=false;
		 while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-'));
		 if(b=='-'){
			 minus=true;
			 b=readByte();
		 }
		 for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0');
		 return minus ? -res:res;
	 }
	 private static long nl(){
		 long res=0,b;
		 boolean minus=false;
		 while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-'));
		 if(b=='-'){
			 minus=true;
			 b=readByte();
		 }
		 for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0');
		 return minus ? -res:res;
	}
}


import java.util.*;

public class Program
{
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		int a,b,c,t = 1, t0;
		boolean espera = true;
		//Console.WriteLine("Digite o tamanho dos dados/s do video :  ");
		a = s.nextInt();;
		//Console.WriteLine("Digite a capacidade de dowload de dados/s :  ");
		b = s.nextInt();;
		//Console.WriteLine("Digite o tamanho do video em segundos :  ");
		c = s.nextInt();;
		//System.out.println(a + " " + b + " " + c);
		if (b == 1)
        {
                Console.WriteLine((a * c) - c);
        }
		else
		{
			while ( a * c > t* b ) //while (a * c > t * b)
				{
					//Console.WriteLine("tempo:" + t);

					for (t0 = 1; t0 <= t+c ; t0++)
					{

						if ((t0)*b >= (a * c)-(t*b) && t0+t<=t+c && espera)
						{
							System.out.println(t);

							t0 = t + 1;
							espera = false;

						}
					}
					t++;

				}
			}

	}

}


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

public class Program
{
	public static void main(String[] args)
	{
		int a,b,c,t = 0, t0 = 0;
		//Console.WriteLine("Digite o tamanho dos dados/s do video :  ");
		a = System.in.read();
		//Console.WriteLine("Digite a capacidade de dowload de dados/s :  ");
		b = System.in.read();
		//Console.WriteLine("Digite o tamanho do video em segundos :  ");
		c = System.in.read();
		//System.out.println(a + " " + b + " " + c);

		while (a * c > t * b) //for (t = 0;   ; t++)
		{
			 if ((a * c) - (t * b) < (t * b) && ((t * b) / b) + (t * b) >= a * c)
			 {
						t0 = t;
						t = c * a;
			 }
			t++;
		}
		System.out.println("" + t0);

	}

}


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

public class Program
{
	public static void main(String[] args)
	{
		int a,b,c,t = 0, t0 = 0;
		//Console.WriteLine("Digite o tamanho dos dados/s do video :  ");
		a = System.in.read();
		//Console.WriteLine("Digite a capacidade de dowload de dados/s :  ");
		b = System.in.read();
		//Console.WriteLine("Digite o tamanho do video em segundos :  ");
		c = System.in.read();
		System.out.println(a + " " + b + " " + c);

		while (a * c > t * b) //for (t = 0;   ; t++)
		{
			 if ((a * c) - (t * b) < (t * b) && ((t * b) / b) + (t * b) >= a * c)
			 {
						t0 = t;
						t = c * a;
			 }
			t++;
		}
		System.out.println("" + t0);

	}

}


import java.util.*;

public class Program
{
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		int a,b,c,t = 1, t0;
		boolean espera = true;
		//Console.WriteLine("Digite o tamanho dos dados/s do video :  ");
		a = s.nextInt();;
		//Console.WriteLine("Digite a capacidade de dowload de dados/s :  ");
		b = s.nextInt();;
		//Console.WriteLine("Digite o tamanho do video em segundos :  ");
		c = s.nextInt();;
		//System.out.println(a + " " + b + " " + c);
		for (t = 1; a * c > t * b; t++) //while (a * c > t * b)
            {
                //Console.WriteLine("tempo:" + t);
                //Console.WriteLine("valor de t: " + t + " T  " + t * b);
                espera = true;
                for (t0 = t; t0 <= t + c; t0++)
                {
                    //Console.WriteLine("valor de t0: "+t0+" TO  "+t0*b);
                    if (t0 * b < (t0 - t) * a )
                        espera = false;
                }
                if (espera)
                {
                    Console.WriteLine(t);
                    break;
                }

            }

	}

}


/**
 * Created by IntelliJ IDEA.
 * User: Taras_Brzezinsky
 * Date: 9/13/11
 * Time: 5:34 PM
 * To change this template use File | Settings | File Templates.
 */

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

public class TaskE extends Thread {
    public TaskE() {
        this.input = new BufferedReader(new InputStreamReader(System.in));
        this.output = new PrintWriter(System.out);
        this.setPriority(Thread.MAX_PRIORITY);
    }

    static final long doit(int mask, int dead, int n) {
        if ((mask & dead) == 0) {
            cache[mask][dead] = 0;
            return 0;
        }
        if (cache[mask][dead] != -1) {
            return cache[mask][dead];
        }
        long result = 0;
        for (int a = 0; a < n; ++a) {
            if (((mask & (1 << a)) != 0) && ((dead & (1 << a)) != 0)) {
                for (int b = 0; b < n; ++b) {
                    if (g[a][b] && (mask & (1 << b)) != 0) {
                        if (mask == ((1 << a) | (1 << b))) {
                            cache[mask][dead] = ((dead & mask) == mask) ? 1 : 0;
                            return cache[mask][dead];
                        }
                        if ((dead & (1 << b)) == 0) {
                            result += doit(mask ^ (1 << a), dead, n) + doit(mask ^ (1 << a), dead ^ (1 << b), n);
                        }
                    }
                }
                break;
            }
        }
        cache[mask][dead] = result;
        return result;
    }

    private void solve() throws Throwable {
        int n = nextInt(), m = nextInt(), k = nextInt();
        g = new boolean[n][n];
        cache = new long[1 << n][1 << n];
        for (long[] current : cache) {
            Arrays.fill(current, -1);
        }
        Arrays.fill(cache[0], 1);
        for (int i = 0; i < m; ++i) {
            int a = nextInt() - 1, b = nextInt() - 1;
            g[a][b] = g[b][a] = true;
        }
        long ans = 0;
        for (int dead = 0; dead < (1 << n); ++dead) {
            if (Integer.bitCount(dead) == k) {
                ans += doit((1 << n) - 1, dead, n);
            }
        }
        output.println(ans);

    }

    public void run() {
        try {
            solve();
        } catch (Throwable e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(666);
        } finally {
            output.flush();
            output.close();
        }
    }

    public static void main(String[] args) {
        new TaskE().start();
    }

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

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

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

    private String nextToken() throws IOException {
        while (tokens == null || !tokens.hasMoreTokens()) {
            tokens = new StringTokenizer(input.readLine());
        }
        return tokens.nextToken();
    }

    static long[][] cache;
    static boolean[][] g;
    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer tokens = null;
}


import java.util.Scanner;

public class E {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int k = sc.nextInt();
		int[][]a = new int[n][n];
		int[][]dp = new int[1 << n][1 << n];
		for (int i = 1; i <= m; i++) {
			int v1 = sc.nextInt();
			int v2 = sc.nextInt();
			v1--;
			v2--;
			a[v1][v2] = a[v2][v1] = 1;
			dp[(1 << v1) | (1 << v2)][(1 << v1) | (1 << v2)] = 1;
		}
		for (int mask = 0; mask < (1 << n); mask++) {
			for (int subm = mask; subm != 0; subm = ((subm-1) & mask)) {
				if (dp[mask][subm]==0)
					continue;
				for (int i = 0; i < n; i++) {
					if ((mask & (1 << i)) != 0) {
						for (int j = 0; j < n; j++) {
							if ((mask & (1 << j))==0 && a[i][j]==1) {
								int new_subm = (subm | (1 << j));
								if ((subm & (1 << i)) != 0)
									new_subm ^= (1 << i);
								int q = (1 << n)-(1 << (j+1));
								if ((new_subm & q) != 0)
										continue;
								dp[mask | (1 << j)][new_subm] += dp[mask][subm];
							}
						}
					}
				}
			}
		}
		int ans = 0;
		for (int mask = 0; mask < (1 << n); mask++) {
			if (Integer.bitCount(mask)==k)
				ans += dp[(1 << n)-1][mask];
		}
		System.out.println(ans);
	}

}


import java.util.*;
public class E {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		n = s.nextInt();
		m = s.nextInt();
		k = s.nextInt();
		a = new int[m][];
		for (int i = 0; i < m; ++i) {
			int u = s.nextInt() - 1, v = s.nextInt() - 1;
			a[i] = new int[] { u, v };
		}
		b = new boolean[m];
		System.out.println(f(-1, m));
	}

	static int n, m, k;
	static int[][] a;
	static boolean[] b;

	static int f(int x, int en) {
		if (en == n - 1) {
			int[] cs = new int[n];
			UnionFind uf = new UnionFind(n);
			for (int i = 0; i < m; ++i) {
				if (!b[i]) {
					++cs[a[i][0]];
					++cs[a[i][1]];
					if(!uf.isSame(a[i][0], a[i][1])){
						uf.unite(a[i][0], a[i][1]);
					}else{
						return 0;
					}
				}
			}
			int cnt = 0;
			for (int c : cs) {
				if (c == 1) {
					++cnt;
				}
			}
			return cnt == k ? 1 : 0;
		}
		int result = 0;
		for (int i = x + 1; i < m; ++i) {
			if (!b[i]) {
				b[i] = true;
				result += f(i, en - 1);
				b[i] = false;
			}
		}
		return result;
	}

	static class UnionFind {
		int[] par;
		int[] rank;

		public UnionFind(int n) {
			par = new int[n];
			rank = new int[n];
			for (int i = 0; i < n; ++i) {
				par[i] = i;
				rank[i] = 0;
			}
		}

		int find(int x) {
			return (par[x] == x) ? x : (par[x] = find(par[x]));
		}

		void unite(int x, int y) {
			x = find(x);
			y = find(y);
			if (x == y)
				return;
			if (rank[x] < rank[y]) {
				par[x] = y;
			} else {
				par[y] = x;
				if (rank[x] == rank[y])
					++rank[x];
			}
		}

		boolean isSame(int x, int y) {
			return find(x) == find(y);
		}
	}
}


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: piyushd
 * Date: 1/7/11
 * Time: 12:04 AM
 * To change this template use File | Settings | File Templates.
 */
public class DeadEnds {

	int[][] roads;
	int N, M, K;

	int pos(long n){
		return (int)(Math.log(n) / Math.log(2) + 1e-7);
	}

	long ways(int cnt, int road, long mask, int[] par){
		long res = 0;

		if(cnt == N - 1){

			int[] usedJunctions = new int[N];
			for(long j = mask, i = j & (j - 1); j > 0; j = i, i &= (i - 1)){
				usedJunctions[roads[pos(j - i)][0]]++;
				usedJunctions[roads[pos(j - i)][1]]++;
			}

			int dead = 0;
			for(int i = 0; i < N; i++) if(usedJunctions[i] == 1) dead++;

			if(dead == K) return 1;
			else return 0;

		}

		if(road == M) return res;

		if(par[roads[road][0]] != par[roads[road][1]]){

			mask += (1L<<road);
			int[] npar = Arrays.copyOf(par, par.length);
			int x = npar[roads[road][1]];
			for(int i = 0; i < N; i++){
				if(npar[i] == x){
					npar[i] = npar[roads[road][0]];
				}
			}

			res += ways(cnt + 1, road + 1, mask, npar);
		}

		if((mask & (1L<<road)) > 0) mask -= (1L<<road);
		res += ways(cnt, road + 1, mask, par);
		return res;
	}

    void run(){
		N = nextInt(); M = nextInt(); K = nextInt();
		roads = new int[M][2];
		for(int i = 0; i < M; i++){
			roads[i][0] = nextInt() - 1;
			roads[i][1] = nextInt() - 1;
		}

		int[] par = new int[N];
		for(int i = 0; i < N; i++) par[i] = i;

		System.out.println(ways(0, 0, 0, par));
    }

    int nextInt(){
        try{
            int c = System.in.read();
            if(c == -1) return c;
            while(c != '-' && (c < '0' || '9' < c)){
                c = System.in.read();
                if(c == -1) return c;
            }
            if(c == '-') return -nextInt();
            int res = 0;
            do{
                res *= 10;
                res += c - '0';
                c = System.in.read();
            }while('0' <= c && c <= '9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }

    long nextLong(){
        try{
            int c = System.in.read();
            if(c == -1) return -1;
            while(c != '-' && (c < '0' || '9' < c)){
                c = System.in.read();
                if(c == -1) return -1;
            }
            if(c == '-') return -nextLong();
            long res = 0;
            do{
                res *= 10;
                res += c-'0';
                c = System.in.read();
            }while('0' <= c && c <= '9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }

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

    String next(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(Character.isWhitespace(c))
                c = System.in.read();
            do{
                res.append((char)c);
            }while(!Character.isWhitespace(c=System.in.read()));
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

    String nextLine(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(c == '\r' || c == '\n')
                c = System.in.read();
            do{
                res.append((char)c);
                c = System.in.read();
            }while(c != '\r' && c != '\n');
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

    public static void main(String[] args){
        new DeadEnds().run();
    }
}


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

/**
 * @author Don Li
 */
public class SkyFullOfStars2 {

    int N = (int) 1e6 + 10;
    int MOD = 998244353;

    long[] fac = new long[N], ifac = new long[N], inv = new long[N];

    {
        inv[1] = 1;
        for (int i = 2; i < N; i++) inv[i] = (MOD - MOD / i) * inv[MOD % i] % MOD;

        fac[0] = fac[1] = 1;
        ifac[0] = ifac[1] = 1;
        for (int i = 2; i < N; i++) {
            fac[i] = fac[i - 1] * i % MOD;
            ifac[i] = ifac[i - 1] * inv[i] % MOD;
        }
    }

    int n;

    void solve() {
        n = in.nextInt();

        long[] c = new long[n + 1];
        c[0] = 1;
        for (int i = 1; i <= n; i++) c[i] = fac[n] * ifac[i] % MOD * ifac[n - i] % MOD;

        long ans = 0;
        for (int i = 0; i < n; i++) {
            long delta = c[i] * (pow((1 - pow(3, i) + MOD) % MOD, n) - pow((MOD - pow(3, i)) % MOD, n) + MOD) % MOD;
            if ((i + 1) % 2 == 0) ans = (ans + delta) % MOD;
            else ans = (ans - delta + MOD) % MOD;
        }
        ans = 3 * ans % MOD;

        for (int i = 1; i <= n; i++) {
            long delta = 2 * c[i] % MOD * pow(3, i + (long) n * (n - i)) % MOD;
            if (i % 2 == 1) ans = (ans + delta) % MOD;
            else ans = (ans - delta + MOD) % MOD;
        }

        out.println(ans);
    }

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

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new SkyFullOfStars2().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CSkyFullOfStars solver = new CSkyFullOfStars();
        solver.solve(1, in, out);
        out.close();
    }

    static class CSkyFullOfStars {
        NumberTheory.Mod998 mod = new NumberTheory.Mod998();
        private static final int Z = 3;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();

            long first = 0;
            long zN = mod.pow(Z, n);
            long zK = 1;
            long zNNK = mod.pow(zN, n);
            long zNinv = mod.inv(zN);
            for (int k = 0; k <= n; k++) {
                long term = mod.mult(mod.ncr(n, k), zK, zNNK, parity(k));
                first = mod.add(first, term);
                zK = mod.mult(zK, Z);
                zNNK = mod.mult(zNNK, zNinv);
            }
            first = mod.mult(first, 2);
            first = mod.subtract(first, mod.pow(Z, (long) n * n));

            long second = 0;
            long zKN = mod.pow(Z, 1 - n);
            for (int k = 1; k <= n; k++) {
                long pow = mod.pow(Z, (long) n * n - (long) n * k + 1);
                long x = mod.mult(mod.ncr(n, k), pow, parity(k));
                long summation = mod.add(mod.negative(1), mod.pow(mod.subtract(1, zKN), n));
                second = mod.add(second, mod.mult(x, summation));
                zKN = mod.mult(zKN, Z);
            }

            long answer = mod.add(first, second);
            answer = mod.subtract(mod.pow(Z, (long) n * n), answer);

            out.println(answer);
        }

        private long parity(int k) {
            return (k & 1) == 0 ? 1 : mod.negative(1);
        }

    }

    static class InputReader {
        public final 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());
        }

    }

    static class NumberTheory {
        private static void ASSERT(boolean assertion) {
            if (!assertion)
                throw new AssertionError();
        }

        public abstract static class Modulus<M extends NumberTheory.Modulus<M>> {
            final ArrayList<Long> factorial = new ArrayList<>();
            final ArrayList<Long> invFactorial = new ArrayList<>();

            public abstract long modulus();

            public Modulus() {
                super();
                factorial.add(1L);
                invFactorial.add(1L);
            }

            public long fact(int n) {
                while (factorial.size() <= n) {
                    factorial.add(mult(factorial.get(factorial.size() - 1), factorial.size()));
                }

                return factorial.get(n);
            }

            public long fInv(int n) {
                int lastKnown = invFactorial.size() - 1;

                if (lastKnown < n) {
                    long[] fInv = new long[n - lastKnown];
                    fInv[0] = inv(fact(n));
                    for (int i = 1; i < fInv.length; i++) {
                        fInv[i] = mult(fInv[i - 1], n - i + 1);
                    }
                    for (int i = fInv.length - 1; i >= 0; i--) {
                        invFactorial.add(fInv[i]);
                    }
                }

                return invFactorial.get(n);
            }

            public long ncr(int n, int r) {
                ASSERT(n >= 0);
                if (r < 0 || n < r)
                    return 0;
                return mult(fact(n), mult(fInv(r), fInv(n - r)));
            }

            public long normalize(long x) {
                x %= modulus();
                if (x < 0)
                    x += modulus();
                return x;
            }

            public long add(long a, long b) {
                long v = a + b;
                return v < modulus() ? v : v - modulus();
            }

            public long subtract(long a, long b) {
                long v = a - b;
                return v < 0 ? v + modulus() : v;
            }

            public long mult(long... x) {
                long r = 1;
                for (long i : x)
                    r = mult(r, i);
                return r;
            }

            public long mult(long a, long b) {
                return (a * b) % modulus();
            }

            public long negative(long x) {
                return x == 0 ? 0 : modulus() - x;
            }

            public long pow(long x, int e) {
                if (e < 0) {
                    x = inv(x);
                    e *= -1;
                }
                if (e == 0)
                    return 1;
                if ((e & 1) > 0)
                    return mult(x, pow(x, e - 1));
                return pow(mult(x, x), e / 2);
            }

            public long pow(long x, long e) {
                if (e < 0) {
                    x = inv(x);
                    e *= -1;
                }
                if (e == 0)
                    return 1;
                if ((e & 1) > 0)
                    return mult(x, pow(x, e - 1));
                return pow(mult(x, x), e / 2);
            }

            public long inv(long value) {
                long g = modulus(), x = 0, y = 1;
                for (long r = value; r != 0; ) {
                    long q = g / r;
                    g %= r;

                    long temp = g;
                    g = r;
                    r = temp;

                    x -= q * y;

                    temp = x;
                    x = y;
                    y = temp;
                }

                ASSERT(g == 1);
                ASSERT(y == modulus() || y == -modulus());

                return normalize(x);
            }

        }

        public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> {
            public long modulus() {
                return 998_244_353L;
            }

        }

    }
}


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

public class Main {

    void solve() {
        int n=ni();
        precompute(n);
        long ans=(2*f3(n))%M;
        long sm=0;
        for(int i=0;i<n;i++){

            sm=add(sm,f2(i,n),M);
        }
        sm=mul(sm,3,M);
        ans=add(ans,sm,M);
        pw.println(ans);

    }
    long f3(long n){
        if(n==1) return 3;
        long ans=modpow(3,n*n,M);
        long b=modpow((pow[(int)n]-3+M)%M ,n,M);
        ans=sub(ans,b,M);
        return ans;
    }
    long f2(int i,int n){
        long ans=ncr(n,i);
        if(i%2==0) ans*=-1;
        if(ans<0) ans+=M;
        ans=mul(ans,f(i,n),M);
        return ans;
    }
    long f(int i,int n){
        if(i==0){
            if(n%2==0) return -1;
            else return 1;
        }
        long t=modpow(pow[i],n,M);
        long a=t;
        if(n%2==0) a*=-1;
        if(a<0) a+=M;
        long b=(1-pow[i]+M)%M;
        b=modpow(b,n,M);
        long ans=add(a,b,M);
        return ans;
    }
    long ncr(int n,int r){
        long ans=fact[n];
        ans=mul(ans,inv[r],M);
        ans=mul(ans,inv[n-r],M);
        return ans;
    }
    long fact[];
    long pow[];
    long inv[];
    void precompute(int n){
        fact=new long[n+1];
        pow=new long[n+1];
        inv=new long[n+1];
        pow[0]=1;
        fact[0]=1;
        for(int i=1;i<=n;i++) {
            pow[i]=(pow[i-1]*3)%M;
            fact[i]=(fact[i-1]*i)%M;
        }
        inv[n]=modInverse(fact[n],M);
        for(int i=n-1;i>=0;i--){
            inv[i]=(inv[i+1]*(i+1))%M;
        }

    }
    long add(long x, long y,long M) {
        x += y;
        if (x < 0) x+=M;
        if (x >= M) x -=M;
        return x;
    }
    long sub(long x, long y,long M) {
        x -= y;
        if (x < 0) x+=M;
        if (x >= M) x -=M;
        return x;
    }
    long mul(long a, long b,long M)
    {
        return (a*1L*b)%M;
    }
    long modpow(long a, long b,long M)
    {
        long r=1;
        while(b>0)
        {
            if((b&1)>0) r=mul(r,a,M);
            a=mul(a,a,M);
            b>>=1;
        }
        return r;
    }

    long modInverse(long A, long M)
    {

        return modpow(A,M-2,M);
    }

    long M=(long)998244353;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

    public static void main(String[] args) throws Exception { new Main().run(); }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}


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

public class Codeforces998E {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());

		int mod = 998244353;
		int phimod = mod-1;

		int[] factorial = new int[n+1];
		factorial[0] = 1;
		for (int i = 1; i <= n; i++) {
			factorial[i] = (int) (((long) factorial[i-1] * i)%mod);
		}

		int[] choose = new int[n+1];
		for (int i = 0; i <= n; i++) {
			int r = inverse(factorial[i], mod);
			int s = inverse(factorial[n-i], mod);
			int rs = (int) (((long) r * (long) s)%mod);
			choose[i] = (int) (((long) rs * (long) factorial[n])%mod);
		}

		int sum1 = 0;
		int threepower = 1;
		for (int i = 0; i <= n; i++) {
			int u = (mod+1 - threepower)%mod;
			int upower = power(u, n, mod);
			int summand = (int) (((long) choose[i] * (long) upower)%mod);
			if (i%2 == 0) {
				summand = mod-summand;
			}
			sum1 = (sum1+summand)%mod;

			threepower = (int) ((3 * (long) threepower)%mod);
		}
		sum1 = (int) ((3 * (long) sum1)%mod);

		int sum2 = power(power(3, n, mod)-1, n, mod);
		sum2 = (2*sum2)%mod;
		sum2 = (sum2+mod-power(3, power(n, 2, phimod), mod))%mod;
		sum2 = (int) ((3 * (long) sum2)%mod);

		int sum3 = power(power(3, n-1, mod)-1, n, mod);
		int aaa = (int) (((long) n * (long) (n-1))%phimod);
		sum3 = (mod + power(3, aaa, mod) - sum3)%mod;
		sum3 = (2*sum3)%mod;
		sum3 = (int) ((long) sum3 * (long) power(3, n, mod)%mod);

		int sum = sum1;
		sum = (sum+sum2)%mod;
		sum = (sum+sum3)%mod;

		System.out.println(sum);
	}

	public static int power(int base, int exp, int mod) {
		long a = base%mod;
		if (exp == 0) {
			return 1;
		}
		else {
			a = (a*a)%mod;
			int b = (int) a;
			int almostanswer = power(b, exp/2, mod);
			if (exp%2 == 0) {
				return almostanswer;
			}
			else {
				long val = (long) almostanswer * (long) base;
				long val2 = val%mod;
				return (int) val2;
			}
		}
	}

	public static int inverse (int a, int n) {
		int m = n;
		int r1 = 1;
		int r2 = 0;
		int r3 = 0;
		int r4 = 1;
		while ((a > 0) && (n > 0)) {
			if (n >= a) {
				r3 -= r1*(n/a);
				r4 -= r2*(n/a);
				n = n%a;
			}
			else {
				int tmp = a;
				a = n;
				n = tmp;
				tmp = r1;
				r1 = r3;
				r3 = tmp;
				tmp = r2;
				r2 = r4;
				r4 = tmp;
			}
		}
		if (a == 0) {
			if (r3 >= 0)
				return (r3%m);
			else
				return (m+(r3%m));
		}
		else {
			if (r1 >= 0)
				return (r1%m);
			else
				return (m+(r1%m));
		}

	}
}


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

public class LenghteningSticks {
	private static final BufferedReader in = new BufferedReader(
			new InputStreamReader(System.in));

	public boolean isTriangle(int a, int b, int c) {
		return (a + b > c && a + c > b && b + c > a);
	}

	public void solve() throws IOException {
		String[] next = in.readLine().split(" ");
		int a = Integer.parseInt(next[0]);
		int b = Integer.parseInt(next[1]);
		int c = Integer.parseInt(next[2]);
		int l = Integer.parseInt(next[3]);

		long ways = 0;
		int bad = 0;
		for (int i = 0; i <= l; i++) {
			// length of one side >= second = third side + whats left of l
			if (a + i > b + c + l - i) break;
			for (int j = 0; i + j <= l; j++) {
			if (b + j > a + i + c + l - i - j) break;

				int x = Math.min(a + i, b + j);
				int y = Math.max(a + i, b + j);
				int minC = Math.max(y - x + 1, c);
				int maxC = Math.min(x + y - 1, c + l - i - j);
				if (maxC >= minC) { ways += maxC - minC + 1; }
				//else bad++;
			}
		}
		//System.out.println(bad);
		System.out.println(ways);
		in.close();
	}

	public static void main(String[] args) throws IOException {
		new LenghteningSticks().solve();
	}
}


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

public class Main {
    public void solve() {
        int a = ni(), b = ni(), c = ni(), l = ni();
        int x, y ,z;
        if ((a > b) && (a > c)) {
            x = a;
            if (b > c) {
                y = b;
                z = c;
            } else {
                y = c;
                z = b;
            }
        } else if (b > c) {
            x = b;
            if (a > c) {
                y = a;
                z = c;
            } else {
                y = c;
                z = a;
            }
        } else {
            x = c;
            if (b > a) {
                y = b;
                z = a;
            } else {
                y = a;
                z = b;
            }
        }

        long ans = 0;
        for (int i = x; l - (i - x) - (Math.max(0, i - (y + z) + 1)) >= 0; i++) {
            for (int j = y; l - (i - x) - (j - y) - (Math.max(0, j - (i + z) + 1)) >= 0; j++) {
//                System.out.println(i + " " + j + " " + (l - (i - x) - (j - y)));
                int max = (i + j - 1);
                int min = Math.abs(i - j) + 1;
//                System.out.println("min: " + min + " max: " + max);
                int steps = l - (i - x) - (j - y) - Math.max(0, min - z);
                min = Math.max(min, z);
                max = Math.min(max, min + steps);
                ans += Math.max(0, max - min + 1);
//                System.out.println(Math.max(0, max - min + 1));
            }
        }
        write(ans + "\n");
    }

    public static void main(String[] args){
        Main m = new Main();
        m.solve();
        try {
            m.writer.close();
        } catch (IOException e) {};
    }
    BufferedReader reader;
    BufferedWriter writer;
    StringTokenizer tokenizer;
    public Main() {
        reader = new BufferedReader(new InputStreamReader(System.in));
        writer = new BufferedWriter(new OutputStreamWriter(System.out));
    }
    int ni() {
        return Integer.parseInt(n());
    }
    String n() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {}
        }
        return tokenizer.nextToken();
    }
    void write(String s) {
        try {
            writer.write(s);
        } catch(IOException e) {};
    }
}


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

public class LenghteningSticks {
	private static final BufferedReader in = new BufferedReader(
			new InputStreamReader(System.in));

	public boolean isTriangle(int a, int b, int c) {
		return (a + b > c && a + c > b && b + c > a);
	}

	public void solve() throws IOException {
		String[] next = in.readLine().split(" ");
		int a = Integer.parseInt(next[0]);
		int b = Integer.parseInt(next[1]);
		int c = Integer.parseInt(next[2]);
		int l = Integer.parseInt(next[3]);

		long ways = 0;
		for (int i = 0; i <= l; i++) {
			// length of one side >= second = third side + whats left of l
			//if (a + i > b + c + l - i) break;
			for (int j = 0; i + j <= l; j++) {
				//if (b + j > a + c + l - i - j) break;
				for (int k = 0; i + j + k <= l; k++) {
					if (isTriangle(a + i,b + j,c + k)) {
						ways++;
					}
					//else { break; }
				}
			}
		}
		System.out.println(ways);
		in.close();
	}

	public static void main(String[] args) throws IOException {
		new LenghteningSticks().solve();
	}
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public class C
{
	public static final Random RANDOM = new Random(System.currentTimeMillis());
	private BufferedReader bufferedReader;
	private StringTokenizer stringTokenizer;
	private PrintWriter out;

	public C()
	{
		this(new BufferedReader(new InputStreamReader(System.in)));
	}

	public C(BufferedReader bufferedReader)
	{
		this.bufferedReader = bufferedReader;
		this.stringTokenizer = null;
		this.out = new PrintWriter(new BufferedOutputStream(System.out));
	}

	public C(String file) throws FileNotFoundException
	{
		this(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
	}

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

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

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

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

	public String nextLine() throws IOException
	{
		return this.bufferedReader.readLine();
	}

	public void close()
	{
		out.close();
	}

	public static void main(String[] args)
	{
		C template = new C();
		try
		{
			template.solve();
		}
		catch (IOException exception)
		{
			exception.printStackTrace();
		}
		template.close();
	}

	public boolean degenerate(int[] x)
	{
		boolean result = false;
		for (int index = 0; index < 3; index++)
		{
			result |= x[index] >= x[(index + 1) % 3] + x[(index + 2) % 3];
		}
		return result;
	}

	public void solve() throws IOException
	{
		int x[] = new int[3];
		x[0] = nextInt();
		x[1] = nextInt();
		x[2] = nextInt();
		int l = nextInt();
		Arrays.sort(x);
		long result = 0;
		for (int l2 = 0; l2 <= l; l2++)
		{
			for (int l1 = 0; l1 <= l - l2; l1++)
			{
				int x1 = Math.min(x[1] + l1, x[2] + l2);
				int x2 = Math.max(x[1] + l1, x[2] + l2);
				int l0Min = Math.max(0, x2 - x1 - x[0] + 1);
				int l0Max = Math.min(l - l2 - l1, x1 + x2 - x[0] - 1);
//				out.println(x1 + ", " + x2 + ", " + l0Min + "-" + l0Max);
				result += Math.max(0, l0Max - l0Min + 1);
			}
		}
		System.out.println(result);
	}
}


// Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;

// Please name your class Main
public class Main {
    static FastScanner fs=new FastScanner();
    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        public String next() {
            while (!st.hasMoreElements())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }
        int Int() {
            return Integer.parseInt(next());
        }

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

        String Str(){
            return next();
        }
    }

    public static void main (String[] args) throws java.lang.Exception {
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        //reading /writing file
        //Scanner sc=new Scanner(new File("input.txt"));
        //PrintWriter pr=new PrintWriter("output.txt");

        int T=1;
        for(int t=0;t<T;t++){
            String s=Str();

            Solution sol=new Solution(out);
            sol.solution(s);
        }
        out.close();

    }

    public static int[] Arr(int n){
        int A[]=new int[n];
        for(int i=0;i<n;i++)A[i]=Int();
        return A;
    }
    public static int Int(){
        return fs.Int();
    }
    public static long Long(){
        return fs.Long();
    }
    public static String Str(){
        return fs.Str();
    }

}

class Solution{
    PrintWriter out;
    int INF=Integer.MAX_VALUE;
    int MOD=1000000007;
    public Solution(PrintWriter out){
        this.out=out;
    }

    long dp[][][];
    public void solution(String s) {
        dp=new long[s.length()+1][800][800];
        for(int i=0;i<dp.length;i++){
            for(int j=0;j<dp[0].length;j++)Arrays.fill(dp[i][j],-1);
        }
        long res=dfs("0"+s,0,0,0);
        out.println(res);

    }

    public long dfs(String s,int pos,int diff,int chunk){
        if(pos>=s.length()){
            if(diff!=0)return INF;
            return 0;
        }
        if(chunk>350||Math.abs(diff)>350){
            return INF;
        }
        if(dp[pos][diff+400][chunk+400]!=-1)return dp[pos][diff+400][chunk+400];

        int d=s.charAt(pos)-'0';
        long res=INF;
        int newdiff=diff*10+chunk-d;
        for(int i=-6;i<=6;i++){
            long cnt=Math.abs(i)*(s.length()-pos);
            res=Math.min(res,cnt+dfs(s,pos+1,newdiff+i,chunk+i));
        }
        dp[pos][diff+400][chunk+400]=res;
        return res;
    }
}


import java.util.*;
import java.io.*;
public class Edu104F{
	public static void main(String[] main) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		PrintWriter out = new PrintWriter(System.out);
		String s = st.nextToken();
		int[] num = new int[s.length()+1];
		num[1] = s.charAt(0) - 48;
		for(int i = 2; i <= s.length(); i++) {
			num[i] = s.charAt(i-1) - s.charAt(i-2);
		}
		int iters = 0;
		boolean edit = true;
		int min = 10000;
		while(edit) {
			iters++;
			edit = false;
			for(int i = 1; i < s.length(); i++) {
				if(num[i] > 5) {
					num[i-1]++;
					num[i] = num[i]-10;
					num[s.length()]--;
					edit = true;
				}
				else if(num[i] == 5 && num[i-1] < 0) {
					num[i-1]++;
					num[i] = num[i]-10;
					num[s.length()]--;
					edit = true;
				}
				else if(i >= 2 && num[i] == 5 && num[i-1] == 4 && num[i-2] < 0 && (num[s.length()] > 0 || num[s.length()] <= -4)) {
					num[i-2]++;
					num[i-1] = -5;
					num[i] = -5;
					num[s.length()]-=2;
					edit = true;
				}
				else if(i >= 2 && num[i] == 5 && num[i-1] == 4 && num[i-2] < 0 && num[s.length()] < -3 && num[s.length() - 1] > 0) {
					num[i-2]++;
					num[i-1] = -5;
					num[i] = -5;
					num[s.length()]-=2;
					edit = true;
				}
				else if(num[i] == 5 && num[i-1] == 5 && num[s.length()] > 1) {
					num[i-2]++;
					num[i-1] = -4;
					num[i] = -5;
					num[s.length()]-=2;
					edit = true;
				}
				else if(num[i] == 5 && num[i-1] == 5 && num[i-2] == 5) {
					num[i-2]++;
					num[i-1] = -4;
					num[i] = -5;
					num[s.length()]-=2;
					edit = true;
				}
				else if(num[i] < -5) {
					num[i-1]--;
					num[i] = num[i]+10;
					num[s.length()]++;
					edit = true;
				}
				else if(num[i] == -5 && num[i-1] > 0) {
					num[i-1]--;
					num[i] = num[i]+10;
					num[s.length()]++;
					edit = true;
				}
				else if(i >= 2 && num[i] == -5 && num[i-1] == -4 && (num[i-2] > 0) && (num[s.length()] < 0 || num[s.length()] >= 4)) {
					num[i-2]--;
					num[i-1] = 5;
					num[i] = 5;
					num[s.length()]+=2;
					edit = true;
				}
				else if(i >= 2 && num[i] == -5 && num[i-1] == -4 && (num[i-2] == -4 && num[i-3] > 0) && (num[s.length()] < 0 || num[s.length()] >= 4)) {
					num[i-2]--;
					num[i-1] = 5;
					num[i] = 5;
					num[s.length()]+=2;
					edit = true;
				}
				else if(i >= 2 && num[i] == -5 && num[i-1] == -4 && num[i-2] > 0 && num[s.length()] > 3 && num[s.length() - 1] < 0) {
					num[i-2]--;
					num[i-1] = 5;
					num[i] = 5;
					num[s.length()]+=2;
					edit = true;
				}
				else if(num[i] == -5 && num[i-1] == -5 && num[s.length()] < -1) {
					num[i-2]--;
					num[i-1] = 4;
					num[i] = 5;
					num[s.length()]+=2;
					edit = true;
				}
				else if(num[i] == -5 && num[i-1] == -5 && num[i-2] == -5) {
					num[i-2]--;
					num[i-1] = 4;
					num[i] = 5;
					num[s.length()]+=2;
					edit = true;
				}
			}
			if(num[s.length()] > 6) {
				num[s.length()-1]++;
				num[s.length()] -= 11;
				edit = true;
			}
			else if(num[s.length()] >= 5 && num[s.length() - 1] < 0) {
				num[s.length()-1]++;
				num[s.length()] -= 11;
				edit = true;
			}
			else if(s.length() >= 2 && num[s.length()] == 6 && num[s.length()-1] == 4 && num[s.length()-2] < 0) {
				num[s.length()-1]++;
				num[s.length()] -= 11;
				edit = true;
			}
			else if(num[s.length()] < -6) {
				num[s.length()-1]--;
				num[s.length()] += 11;
				edit = true;
			}
			else if(num[s.length()] <= -5 && num[s.length() - 1] > 0) {
				num[s.length()-1]--;
				num[s.length()] += 11;
				edit = true;
			}
			else if(s.length() >= 2 && num[s.length()] == -6 && num[s.length()-1] == -4 && num[s.length()-2] > 0) {
				num[s.length()-1]--;
				num[s.length()] += 11;
				edit = true;
			}
			int ans = 0;
			for(int i = 0; i <= s.length(); i++) {
				//out.print(num[i] + " ");
				ans += (s.length() + 1 - i)*Math.abs(num[i]);
			}
			min = Math.min(ans, min);
			if(iters > 7000000) {
				break;
			}
		}
		int ans = 0;
		for(int i = 0; i <= s.length(); i++) {
			//out.print(num[i] + " ");
			ans += (s.length() + 1 - i)*Math.abs(num[i]);
		}
		out.println(Math.min(min,ans));
		out.close();
	}
}


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

public class F {

    static int N = 250;
    static int M = 28;
    static int INF = (int) 1e9;
    static int[][][][] dp = new int[2][M * 2 + 1][N][N];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder(br.readLine());
        String s = sb.reverse().append("0").toString();

        for (int carry = 0; carry < M * 2 + 1; carry++) {
            for (int cp = 0; cp < N; cp++) {
                for (int cn = 0; cn < N; cn++) {
                    dp[0][carry][cp][cn] = INF;
                }
            }
        }
        dp[0][M][N - 1][N - 1] = 0;

        for (int i = 0; i < s.length(); i++) {
            for (int carry = 0; carry < M * 2 + 1; carry++) {
                for (int cp = 0; cp < N; cp++) {
                    for (int cn = 0; cn < N; cn++) {
                        dp[1][carry][cp][cn] = INF;
                    }
                }
            }
            for (int carry = 0; carry < M * 2 + 1; carry++) {
                for (int cp = N - 1; cp >= 0; cp--) {
                    for (int cn = N - 1; cn >= 0; cn--) {
                        if (dp[0][carry][cp][cn] != INF) {
                            if (cp > 0) {
                                dp[0][carry][cp - 1][cn] = Math.min(dp[0][carry][cp - 1][cn], dp[0][carry][cp][cn]);
                            }
                            if (cn > 0) {
                                dp[0][carry][cp][cn - 1] = Math.min(dp[0][carry][cp][cn - 1], dp[0][carry][cp][cn]);
                            }
                            int rcarry = carry - M;
                            int val = rcarry + cp - cn;
                            int digit = val % 10;
                            if (digit < 0) {
                                digit += 10;
                            }
                            int ncarry = val / 10;
                            if (val < 0 && digit != 0) {
                                --ncarry;
                            }
                            if (digit == s.charAt(i) - '0') {
                                dp[1][ncarry + M][cp][cn] = Math.min(dp[1][ncarry + M][cp][cn],
                                        dp[0][carry][cp][cn] + cp + cn);
                            }
                        }
                    }
                }
            }
            int[][][] tmp = dp[0];
            dp[0] = dp[1];
            dp[1] = tmp;
        }

        int ans = INF;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                ans = Math.min(ans, dp[0][M][i][j]);
            }
        }
        System.out.println(ans);
    }

}