import java.util.*;
import java.io.*;
import static java.lang.Math.*;

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

    void run() throws Exception{
        Scanner sc = new Scanner(System.in);
        //BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
        // only sc.readLine() is available
        int N = sc.nextInt();
        int K = sc.nextInt();
        char[] s = sc.next().toCharArray();
        int[] freq = new int[10];
        for(char c : s)freq[c-'0']++;
        int mn = 1<<30;
        char[] ans = "ERROR".toCharArray();
        for(int d = 0; d < 10; d++){
            int sum = freq[d];
            int[] need = new int[10];
            for(int i = 1; i <= 10 && sum < K; i++){
                if(d-i >= 0){
                    int dif = min(freq[d-i], K-sum);
                    sum += dif;
                    need[d-i] += dif;
                }
                if(d+i < 10){
                    int dif = min(freq[d+i], K-sum);
                    sum += dif;
                    need[d+i] += dif;
                }
            }
            int cost = 0;
            char[] t = new char[s.length];
            for(int i = 0; i < t.length; i++)t[i] = s[i];
            char a = (char)('0' + d);
            for(int i = 0; i < d; i++){
                char c = (char)('0' + i);
                cost += need[i] * abs(d-i);
                for(int j = 0; j < t.length && need[i] > 0; j++){
                    if(s[j] == c){
                        t[j] = a;
                        need[i]--;
                    }
                }
            }
            for(int i = d+1; i < 10; i++){
                char c = (char)('0' + i);
                cost += need[i] * abs(d-i);
                for(int j = t.length-1; j >= 0 && need[i] > 0; j--){
                    if(s[j] == c){
                        t[j] = a;
                        need[i]--;
                    }
                }
            }
            if(cost < mn){
                mn = cost;
                ans = t;
            }
        }
        System.out.println(mn);
        System.out.println(new String(ans));
    }
}


import java.util.*;
import java.io.*;
import static java.lang.Math.*;

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

    void run() throws Exception{
        Scanner sc = new Scanner(System.in);
        //BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
        // only sc.readLine() is available
        int N = sc.nextInt();
        int K = sc.nextInt();
        char[] s = sc.next().toCharArray();
        int[] freq = new int[10];
        for(char c : s)freq[c-'0']++;
        int mn = 1<<30;
        char[] ans = "ERROR".toCharArray();
        for(int d = 0; d < 10; d++){
            int sum = freq[d];
            int[] need = new int[10];
            for(int i = 1; i <= 10 && sum < K; i++){
                if(d+i < 10){
                    int dif = min(freq[d+i], K-sum);
                    sum += dif;
                    need[d+i] += dif;
                }
                if(d-i >= 0){
                    int dif = min(freq[d-i], K-sum);
                    sum += dif;
                    need[d-i] += dif;
                }
            }
            int cost = 0;
            char[] t = new char[s.length];
            for(int i = 0; i < t.length; i++)t[i] = s[i];
            char a = (char)('0' + d);
            for(int i = 0; i < d; i++){
                char c = (char)('0' + i);
                cost += need[i] * abs(d-i);
                for(int j = t.length-1; j >= 0 && need[i] > 0; j--){
                    if(s[j] == c){
                        t[j] = a;
                        need[i]--;
                    }
                }
            }
            for(int i = d+1; i < 10; i++){
                char c = (char)('0' + i);
                cost += need[i] * abs(d-i);
                for(int j = 0; j < t.length && need[i] > 0; j++){
                    if(s[j] == c){
                        t[j] = a;
                        need[i]--;
                    }
                }
            }
            if(cost < mn){
                mn = cost;
                ans = t;
            }
        }
        System.out.println(mn);
        System.out.println(new String(ans));
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
//        int testCount = Integer.parseInt(in.next());
        int testCount = 1;
        for (int i = 1; i <= testCount; i++)
            solver.solve(i, in, out);
        out.close();
    }
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int N = in.readInt();
        int K = in.readInt();
        String num = in.readString();
        int[] cnt = new int[10];
        for (int i = 0; i < N; i++)
            ++cnt[num.charAt(i) - '0'];
//        for (int i = 0;i < 10;i++)
//            System.out.print(cnt[i] + " ");
//        System.out.println();
        int maxD = 0;
        for (int i = 0; i < 10; i++)
            maxD = Math.max(maxD, cnt[i]);
        if (maxD >= K) {
            out.printLine(0);
            out.printLine(num);
            return;
        }
        int cost = N * 10;
        String res = num.toString();
        for (char ci = '0'; ci <= '9'; ci++) {
            StringBuilder cS = new StringBuilder(num);
            int cD = 0, nd = cnt[ci - '0'];
            int U = Math.max(ci - '0', '9' - ci);
            for (int d = 1; d <= U && nd < K; d++) {
                char fi = (char) (ci + d);
                if (fi <= '9') {
                    for (int j = 0; j < N && nd < K; j++)
                        if (cS.charAt(j) == fi) {
                            cS.setCharAt(j, ci);
                            cD += d;
                            ++nd;
                        }
                }
                if (nd == K) break;
                fi = (char) (ci - d);
                if (fi >= '0') {
                    for (int j = N - 1; j >= 0 && nd < K; j--)
                        if (cS.charAt(j) == fi) {
                            char pre = cS.charAt(j);
                            cS.setCharAt(j, ci);
                            cD += d;
                            ++nd;
                        }
                }
            }
            String fS = cS.toString();
//            System.out.println(ci + " " + cD + " " + fS);
            if (cD < cost || (cD == cost && fS.compareTo(res) < 0)) {
                cost = cD;
                res = fS;
            }
        }
        out.printLine(cost);
        out.printLine(res);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1) throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0) return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9') throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9') throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

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


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
//        int testCount = Integer.parseInt(in.next());
        int testCount = 1;
        for (int i = 1; i <= testCount; i++)
            solver.solve(i, in, out);
        out.close();
    }
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int N = in.readInt();
        int K = in.readInt();
        String num = in.readString();
        int[] cnt = new int[10];
        for (int i = 0; i < N; i++)
            ++cnt[num.charAt(i) - '0'];
//        for (int i = 0;i < 10;i++)
//            System.out.print(cnt[i] + " ");
//        System.out.println();
        int maxD = 0;
        for (int i = 0; i < 10; i++)
            maxD = Math.max(maxD, cnt[i]);
        if (maxD >= K) {
            out.printLine(0);
            out.printLine(num);
            return;
        }
        int cost = N*10;
        String res = num.toString();
        for (char ci = '0';ci <= '9';ci++){
            StringBuilder cS = new StringBuilder(num);
            int cD = 0,nd = cnt[ci-'0'];
            for (int j = 0;j < N && nd < K;j++)
                if (cS.charAt(j) > ci){
                    char pre = cS.charAt(j);
                    cS.setCharAt(j,ci);
                    cD += pre-ci;
                    ++nd;
                }
            for (int j = N-1;j >= 0 && nd < K;j--)
                if (cS.charAt(j) < ci){
                    char pre = cS.charAt(j);
                    cS.setCharAt(j,ci);
                    cD += ci-pre;
                    ++nd;
                }
            String fS = cS.toString();
            if (cD < cost || (cD == cost && fS.compareTo(res) < 0)){
                cost = cD;
                res = fS;
            }
        }
        out.printLine(cost);
        out.printLine(res);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1) throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0) return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9') throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9') throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

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


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;

public class Main {
	public static void main(String[] args) throws IOException {
		new Thread(null, new Runnable() {
			public void run() {
				try {
					try {
						if (new File("input.txt").exists())
							System.setIn(new FileInputStream("input.txt"));
					} catch (SecurityException e) {}

					long prevTime = System.currentTimeMillis();
					new Main().run();
					System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms");
					System.err.println("Memory status: " + memoryStatus());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, "1", 1L << 24).start();
	}

	void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
		in.close();
	}

	/***************************************************************
	 * Solution
	 **************************************************************/
	void solve() throws IOException  {
		int n = nextInt();
		int k = nextInt();
		char[] num = nextToken().toCharArray();
		int bc = Integer.MAX_VALUE - 1;
		char[] bn = new char [n];
		fill(bn, (char) 256);
		char[] cn = new char [n];
		for (int d = '0'; d <= '9'; d++) {
			int cc = replace(num, d, cn, k);
			if (bc > cc || bc == cc && less(cn, bn)) {
				bc = cc;
				System.arraycopy(cn, 0, bn, 0, n);
			}
		}
		out.println(bc);
		out.println(bn);
	}

	int[] cnt = new int [10];
	int replace(char[] src, int dig, char[] dst, int need) {
		fill(cnt, 0);
		for (char c : src)
			cnt[c - '0']++;
		int cdig = dig - '0';
		for (int d = 0; d < 10; d++) {
			int ld = cdig - d;
			if (ld >= 0) {
				cnt[ld] = min(cnt[ld], need);
				need -= cnt[ld];
			}
			if (d > 0) {
				int rd = cdig + d;
				if (rd < 10) {
					cnt[rd] = min(cnt[rd], need);
					need -= cnt[rd];
				}
			}
		}
		if (need > 0) return Integer.MAX_VALUE;
		int ret = 0;
		for (int i = 0; i < src.length; i++) {
			dst[i] = src[i];
			int cd = src[i] - '0';
			if (cnt[cd] > 0) {
				cnt[cd]--;
				ret += abs(src[i] - dig);
				dst[i] = (char) dig;
			}
		}
		return ret;
	}

	boolean less(char[] a, char[] b) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] < b[i]) return true;
			if (a[i] > b[i]) return false;
		}
		return false;
	}

	/***************************************************************
	 * Input
	 **************************************************************/
	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}

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

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

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

	int[] nextIntArray(int size) throws IOException {
		int[] ret = new int [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextInt();
		return ret;
	}

	long[] nextLongArray(int size) throws IOException {
		long[] ret = new long [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextLong();
		return ret;
	}

	double[] nextDoubleArray(int size) throws IOException {
		double[] ret = new double [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextDouble();
		return ret;
	}

	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}

	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}

	/***************************************************************
	 * Output
	 **************************************************************/
	void printRepeat(String s, int count) {
		for (int i = 0; i < count; i++)
			out.print(s);
	}

	void printArray(int[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(long[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array, String spec) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.printf(Locale.US, spec, array[i]);
		}
		out.println();
	}

	void printArray(Object[] array) {
		boolean blank = false;
		for (Object x : array) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	@SuppressWarnings("rawtypes")
	void printCollection(Collection collection) {
		boolean blank = false;
		for (Object x : collection) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	/***************************************************************
	 * Utility
	 **************************************************************/
	static String memoryStatus() {
		return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
	}

	static void checkMemory() {
		System.err.println(memoryStatus());
	}

	static long prevTimeStamp = Long.MIN_VALUE;

	static void updateTimer() {
		prevTimeStamp = System.currentTimeMillis();
	}

	static long elapsedTime() {
		return (System.currentTimeMillis() - prevTimeStamp);
	}

	static void checkTimer() {
		System.err.println(elapsedTime() + " ms");
	}
}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;

public class Main {
	public static void main(String[] args) throws IOException {
		new Thread(null, new Runnable() {
			public void run() {
				try {
					try {
						if (new File("input.txt").exists())
							System.setIn(new FileInputStream("input.txt"));
					} catch (SecurityException e) {}

					long prevTime = System.currentTimeMillis();
					new Main().run();
					System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms");
					System.err.println("Memory status: " + memoryStatus());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, "1", 1L << 24).start();
	}

	void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
		in.close();
	}

	/***************************************************************
	 * Solution
	 **************************************************************/
	void solve() throws IOException  {
		int n = nextInt();
		int k = nextInt();
		char[] num = nextToken().toCharArray();
		int bc = Integer.MAX_VALUE - 1;
		char[] bn = new char [n];
		fill(bn, (char) 256);
		char[] cn = new char [n];
		for (int d = '0'; d <= '9'; d++) {
			int cc = replace(num, d, cn, k);
			if (bc > cc || bc == cc && less(cn, bn)) {
				bc = cc;
				System.arraycopy(cn, 0, bn, 0, n);
			}
		}
		out.println(bc);
		out.println(bn);
	}

	int[] cnt = new int [10];
	int replace(char[] src, int dig, char[] dst, int need) {
		fill(cnt, 0);
		for (char c : src)
			cnt[c - '0']++;
		int cdig = dig - '0';
		for (int d = 0; d < 10; d++) {
			int rd = cdig + d;
			if (rd < 10) {
				cnt[rd] = min(cnt[rd], need);
				need -= cnt[rd];
			}
			if (d > 0) {
				int ld = cdig - d;
				if (ld >= 0) {
					cnt[ld] = min(cnt[ld], need);
					need -= cnt[ld];
				}
			}
		}
		if (need > 0) return Integer.MAX_VALUE;
		int ret = 0;
		System.arraycopy(src, 0, dst, 0, src.length);
		for (int i = 0; i < src.length; i++) {
			if (src[i] < dig) continue;
			dst[i] = src[i];
			int cd = src[i] - '0';
			if (cnt[cd] > 0) {
				cnt[cd]--;
				ret += abs(src[i] - dig);
				dst[i] = (char) dig;
			}
		}
		for (int i = src.length - 1; i >= 0; i--) {
			if (src[i] > dig) continue;
			dst[i] = src[i];
			int cd = src[i] - '0';
			if (cnt[cd] > 0) {
				cnt[cd]--;
				ret += abs(src[i] - dig);
				dst[i] = (char) dig;
			}
		}
		return ret;
	}

	boolean less(char[] a, char[] b) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] < b[i]) return true;
			if (a[i] > b[i]) return false;
		}
		return false;
	}

	/***************************************************************
	 * Input
	 **************************************************************/
	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}

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

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

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

	int[] nextIntArray(int size) throws IOException {
		int[] ret = new int [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextInt();
		return ret;
	}

	long[] nextLongArray(int size) throws IOException {
		long[] ret = new long [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextLong();
		return ret;
	}

	double[] nextDoubleArray(int size) throws IOException {
		double[] ret = new double [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextDouble();
		return ret;
	}

	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}

	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}

	/***************************************************************
	 * Output
	 **************************************************************/
	void printRepeat(String s, int count) {
		for (int i = 0; i < count; i++)
			out.print(s);
	}

	void printArray(int[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(long[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array, String spec) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.printf(Locale.US, spec, array[i]);
		}
		out.println();
	}

	void printArray(Object[] array) {
		boolean blank = false;
		for (Object x : array) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	@SuppressWarnings("rawtypes")
	void printCollection(Collection collection) {
		boolean blank = false;
		for (Object x : collection) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	/***************************************************************
	 * Utility
	 **************************************************************/
	static String memoryStatus() {
		return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
	}

	static void checkMemory() {
		System.err.println(memoryStatus());
	}

	static long prevTimeStamp = Long.MIN_VALUE;

	static void updateTimer() {
		prevTimeStamp = System.currentTimeMillis();
	}

	static long elapsedTime() {
		return (System.currentTimeMillis() - prevTimeStamp);
	}

	static void checkTimer() {
		System.err.println(elapsedTime() + " ms");
	}
}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;

public class Main {
	public static void main(String[] args) throws IOException {
		new Thread(null, new Runnable() {
			public void run() {
				try {
					try {
						if (new File("input.txt").exists())
							System.setIn(new FileInputStream("input.txt"));
					} catch (SecurityException e) {}

					long prevTime = System.currentTimeMillis();
					new Main().run();
					System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms");
					System.err.println("Memory status: " + memoryStatus());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, "1", 1L << 24).start();
	}

	void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
		in.close();
	}

	/***************************************************************
	 * Solution
	 **************************************************************/
	void solve() throws IOException  {
		int n = nextInt();
		int k = nextInt();
		char[] num = nextToken().toCharArray();
		int bc = Integer.MAX_VALUE - 1;
		char[] bn = new char [n];
		fill(bn, (char) 256);
		char[] cn = new char [n];
		for (int d = '0'; d <= '9'; d++) {
			int cc = replace(num, d, cn, k);
			if (bc > cc || bc == cc && less(cn, bn)) {
				bc = cc;
				System.arraycopy(cn, 0, bn, 0, n);
			}
		}
		out.println(bc);
		out.println(bn);
	}

	int[] cnt = new int [10];
	int replace(char[] src, int dig, char[] dst, int need) {
		fill(cnt, 0);
		for (char c : src)
			cnt[c - '0']++;
		int cdig = dig - '0';
		for (int d = 0; d < 10; d++) {
			int rd = cdig + d;
			if (rd < 10) {
				cnt[rd] = min(cnt[rd], need);
				need -= cnt[rd];
			}
			if (d > 0) {
				int ld = cdig - d;
				if (ld >= 0) {
					cnt[ld] = min(cnt[ld], need);
					need -= cnt[ld];
				}
			}
		}
		if (need > 0) return Integer.MAX_VALUE;
		int ret = 0;
		for (int i = 0; i < src.length; i++) {
			dst[i] = src[i];
			int cd = src[i] - '0';
			if (cnt[cd] > 0) {
				cnt[cd]--;
				ret += abs(src[i] - dig);
				dst[i] = (char) dig;
			}
		}
		return ret;
	}

	boolean less(char[] a, char[] b) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] < b[i]) return true;
			if (a[i] > b[i]) return false;
		}
		return false;
	}

	/***************************************************************
	 * Input
	 **************************************************************/
	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}

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

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

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

	int[] nextIntArray(int size) throws IOException {
		int[] ret = new int [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextInt();
		return ret;
	}

	long[] nextLongArray(int size) throws IOException {
		long[] ret = new long [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextLong();
		return ret;
	}

	double[] nextDoubleArray(int size) throws IOException {
		double[] ret = new double [size];
		for (int i = 0; i < size; i++)
			ret[i] = nextDouble();
		return ret;
	}

	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}

	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}

	/***************************************************************
	 * Output
	 **************************************************************/
	void printRepeat(String s, int count) {
		for (int i = 0; i < count; i++)
			out.print(s);
	}

	void printArray(int[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(long[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array, String spec) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0) out.print(' ');
			out.printf(Locale.US, spec, array[i]);
		}
		out.println();
	}

	void printArray(Object[] array) {
		boolean blank = false;
		for (Object x : array) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	@SuppressWarnings("rawtypes")
	void printCollection(Collection collection) {
		boolean blank = false;
		for (Object x : collection) {
			if (blank) out.print(' '); else blank = true;
			out.print(x);
		}
		out.println();
	}

	/***************************************************************
	 * Utility
	 **************************************************************/
	static String memoryStatus() {
		return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
	}

	static void checkMemory() {
		System.err.println(memoryStatus());
	}

	static long prevTimeStamp = Long.MIN_VALUE;

	static void updateTimer() {
		prevTimeStamp = System.currentTimeMillis();
	}

	static long elapsedTime() {
		return (System.currentTimeMillis() - prevTimeStamp);
	}

	static void checkTimer() {
		System.err.println(elapsedTime() + " ms");
	}
}


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

public class C implements Runnable {

    public void solve( ) throws Throwable {
        int digits[ ] = new int[ 10 ];
        int n = in.nextInt( ), reqd = in.nextInt( );

        char numCh[ ] = in.next( ).toCharArray( );

        int cost = 0;
        for ( char c : numCh ) {
            ++digits[ ( int )( c - '0' ) ];
            if ( digits[ ( int )( c - '0' ) ] >= reqd ) {
                out.println( 0 );
                out.println( new String( numCh ) );
                return;
            }
        }

        char minCh[ ] = numCh;
        int minSum = Integer.MAX_VALUE;
        //debug( digits );
        for ( int d = 0; d < 10; ++d ) {
            int cur = digits[ d ];
            char pat[ ] = ( char[ ] )numCh.clone( );
            int sum = 0;
            for ( int x = 1; x < 10; ++x ) {
                if ( d + x < 10 ) {
                    char y = ( char )( '0' + d + x );
                    for ( int i = 0; cur < reqd && i < n; ++i ) {
                        if ( y == pat[ i ] ) {
                            pat[ i ] = ( char )( d + '0' );
                            sum += x;
                            ++cur;
                        }
                    }
                    //for ( int
                }

                if ( d - x >= 0 ) {
                    char y = ( char )( '0' + d - x );
                    for ( int i = n - 1; cur < reqd && i >= 0; --i ) {

                        if ( y == pat[ i ] ) {
                            pat[ i ] = ( char )( d + '0' );
                            sum += x;
                            ++cur;
                        }
                    }
                }
            }

            if ( minSum > sum || ( sum == minSum && new String( pat ).compareTo( new String( minCh ) ) < 0 ) ) {
                minSum = sum;
                minCh = pat;
            }
        }

        out.println( minSum );
        out.println( new String( minCh ) );

    }

    public void run( ) {
        in = new FastScanner( System.in );
        out = new PrintWriter( new PrintStream( System.out ), true );

        try {
            solve( );
            out.close( );
            System.exit( 0 );
        } catch( Throwable e ) {
            e.printStackTrace( );
            System.exit( -1 );
        }
    }

    public void debug( Object...os ) {
        System.err.println( Arrays.deepToString( os ) );
    }

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

    private FastScanner in;
    private PrintWriter out;

    private static class FastScanner {
        private int charsRead;
        private int currentRead;
        private byte buffer[ ] = new byte[ 0x1000 ];
        private InputStream reader;

        public FastScanner( InputStream in ) {
            reader = in;
        }

        public int read( ) {
            if ( currentRead == -1 ) {
                throw  new InputMismatchException( );
            }

            if ( currentRead >= charsRead ) {
                currentRead = 0;
                try {
                    charsRead = reader.read( buffer );

                } catch( IOException e ) {
                    throw new InputMismatchException(  );
                }

                if ( charsRead <= 0 ) {
                    return -1;
                }
            }

            return buffer[ currentRead++ ];
        }

        public int nextInt( ) {
            int c = read( );

            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;
            if ( sign == -1 ) {
                c = read( );
            }

            if ( c == -1 || !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int ans = 0;
            while ( !isWhitespace( c )  && c != -1 ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw  new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10 + num;
                c = read( );
            }

            return ans * sign;
        }

        public long nextLong( ) {
            int c = read( );

            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;
            if ( sign == -1 ) {
                c = read( );
            }

            if ( c == -1 || !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            long ans = 0;
            while ( !isWhitespace( c )  && c != -1 ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw  new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10 + num;
                c = read( );
            }

            return ans * sign;
        }

        public boolean isWhitespace( int c ) {
            return  c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
        }

        public String next( ) {
            int c = read( );
            StringBuffer ans = new StringBuffer( );

            while ( isWhitespace( c ) && c != -1 ) {
                c  = read( );
            }

            if ( c == -1 ) {
                return null;
            }

            while ( !isWhitespace( c ) && c != -1 ) {
                ans.appendCodePoint( c );
                c = read( );
            }

            return ans.toString( );

        }

        public String nextLine( ) {
            String ans = nextLine0( );

            while ( ans.trim( ).length( ) == 0 ) {
                ans = nextLine0( );
            }

            return ans;
        }

        private String nextLine0( ) {
            int c = read( );
            if ( c == -1 ) {
                return null;
            }
            StringBuffer ans = new StringBuffer( );
            while ( c != '\n' && c != '\r' && c != -1 ) {
                ans.appendCodePoint( c );
                c = read( );
            }

            return ans.toString( );

        }

        public double nextDouble( ) {
            int c = read( );
            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '.' && c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;

            double ans = 0;
            while ( c != -1 && c != '.' && !isWhitespace( c ) ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw new InputMismatchException( );
                }

                int num = c - '0';
                ans = ans * 10.0 + num;
                c = read( );
            }

            if ( !isWhitespace( c ) && c != -1 && c != '.' ) {
                throw new InputMismatchException( );
            }

            double pow10 = 1.0;

            if ( c == '.' ) {
                c = read( );
            }

            while ( !isWhitespace( c ) && c != -1 ) {
                pow10 *= 10.0;

                if ( !( c >= '0' && c <= '9' ) ) {
                    throw new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10.0 + num;
                c = read( );
            }

            return ans * sign / pow10;
        }
    }

}


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

public class C implements Runnable {

    public void solve( ) throws Throwable {
        int digits[ ] = new int[ 10 ];
        int n = in.nextInt( ), reqd = in.nextInt( );

        char numCh[ ] = in.next( ).toCharArray( );

        int cost = 0;
        for ( char c : numCh ) {
            ++digits[ ( int )( c - '0' ) ];
            if ( digits[ ( int )( c - '0' ) ] >= reqd ) {
                out.println( 0 );
                out.println( new String( numCh ) );
                return;
            }
        }

        char minCh[ ] = numCh;
        int minSum = Integer.MAX_VALUE;
        //debug( digits );
        for ( int d = 0; d < 10; ++d ) {
            int cur = digits[ d ];
            char pat[ ] = ( char[ ] )numCh.clone( );
            int sum = 0;
            for ( int x = 1; x < 10; ++x ) {
                if ( d + x < 10 ) {
                    char y = ( char )( '0' + d + x );
                    for ( int i = 0; cur < reqd && i < n; ++i ) {
                        if ( y == pat[ i ] ) {
                            pat[ i ] = ( char )( d + '0' );
                            sum += x;
                            ++cur;
                        }
                    }
                    //for ( int
                }

                if ( d - x >= 0 ) {
                    char y = ( char )( '0' + d - x );
                    for ( int i = n - 1; cur < reqd && i >= 0; --i ) {

                        if ( y == pat[ i ] ) {
                            pat[ i ] = ( char )( d + '0' );
                            sum += x;
                            ++cur;
                        }
                    }
                }
            }

            if ( minSum > sum ) {
                minSum = sum;
                minCh = pat;
            }
        }

        out.println( minSum );
        out.println( new String( minCh ) );

    }

    public void run( ) {
        in = new FastScanner( System.in );
        out = new PrintWriter( new PrintStream( System.out ), true );

        try {
            solve( );
            out.close( );
            System.exit( 0 );
        } catch( Throwable e ) {
            e.printStackTrace( );
            System.exit( -1 );
        }
    }

    public void debug( Object...os ) {
        System.err.println( Arrays.deepToString( os ) );
    }

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

    private FastScanner in;
    private PrintWriter out;

    private static class FastScanner {
        private int charsRead;
        private int currentRead;
        private byte buffer[ ] = new byte[ 0x1000 ];
        private InputStream reader;

        public FastScanner( InputStream in ) {
            reader = in;
        }

        public int read( ) {
            if ( currentRead == -1 ) {
                throw  new InputMismatchException( );
            }

            if ( currentRead >= charsRead ) {
                currentRead = 0;
                try {
                    charsRead = reader.read( buffer );

                } catch( IOException e ) {
                    throw new InputMismatchException(  );
                }

                if ( charsRead <= 0 ) {
                    return -1;
                }
            }

            return buffer[ currentRead++ ];
        }

        public int nextInt( ) {
            int c = read( );

            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;
            if ( sign == -1 ) {
                c = read( );
            }

            if ( c == -1 || !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int ans = 0;
            while ( !isWhitespace( c )  && c != -1 ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw  new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10 + num;
                c = read( );
            }

            return ans * sign;
        }

        public long nextLong( ) {
            int c = read( );

            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;
            if ( sign == -1 ) {
                c = read( );
            }

            if ( c == -1 || !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            long ans = 0;
            while ( !isWhitespace( c )  && c != -1 ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw  new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10 + num;
                c = read( );
            }

            return ans * sign;
        }

        public boolean isWhitespace( int c ) {
            return  c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
        }

        public String next( ) {
            int c = read( );
            StringBuffer ans = new StringBuffer( );

            while ( isWhitespace( c ) && c != -1 ) {
                c  = read( );
            }

            if ( c == -1 ) {
                return null;
            }

            while ( !isWhitespace( c ) && c != -1 ) {
                ans.appendCodePoint( c );
                c = read( );
            }

            return ans.toString( );

        }

        public String nextLine( ) {
            String ans = nextLine0( );

            while ( ans.trim( ).length( ) == 0 ) {
                ans = nextLine0( );
            }

            return ans;
        }

        private String nextLine0( ) {
            int c = read( );
            if ( c == -1 ) {
                return null;
            }
            StringBuffer ans = new StringBuffer( );
            while ( c != '\n' && c != '\r' && c != -1 ) {
                ans.appendCodePoint( c );
                c = read( );
            }

            return ans.toString( );

        }

        public double nextDouble( ) {
            int c = read( );
            while ( isWhitespace( c ) ) {
                c = read( );
            }

            if ( c == -1 ) {
                throw new NullPointerException( );
            }

            if ( c != '.' && c != '-' && !( c >= '0' && c <= '9' ) ) {
                throw new InputMismatchException( );
            }

            int sign = c == '-' ? -1 : 1;

            double ans = 0;
            while ( c != -1 && c != '.' && !isWhitespace( c ) ) {
                if ( !( c >= '0' && c <= '9' ) ) {
                    throw new InputMismatchException( );
                }

                int num = c - '0';
                ans = ans * 10.0 + num;
                c = read( );
            }

            if ( !isWhitespace( c ) && c != -1 && c != '.' ) {
                throw new InputMismatchException( );
            }

            double pow10 = 1.0;

            if ( c == '.' ) {
                c = read( );
            }

            while ( !isWhitespace( c ) && c != -1 ) {
                pow10 *= 10.0;

                if ( !( c >= '0' && c <= '9' ) ) {
                    throw new InputMismatchException( );
                }
                int num = c - '0';
                ans = ans * 10.0 + num;
                c = read( );
            }

            return ans * sign / pow10;
        }
    }

}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Math.min;

public class TaskC {
    public static void main(String[] args) {
        final BufferedInputStream input = new BufferedInputStream(System.in);
        //final Scanner scanner = new Scanner(input);
        doInput(System.in, null);
        //scanner.close();

        solveTask();

        final PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
        doOutput(writer);
        writer.close();
    }

    private static int n, k;
    private static List<Integer> numbers;
    private static List<Integer> counts = new ArrayList<Integer>();
    private static final List<Integer> sums = new ArrayList<Integer>();
    private static final List<List<Integer>> tos = new ArrayList<List<Integer>>();
    private static final List<Integer> index = new ArrayList<Integer>();

    private static void solveTask() {
        counts.clear();
        for (int i = 0; i <= 9; ++i) {
            counts.add(count(numbers, i));
        }

        for (int i = 0; i <= 9; ++i) {
            index.add(i);
        }

        sums.addAll(counts);

        for (int i = 0; i <= 9; ++i) {
            tos.add(calcTo(i));
        }

        for (int i = 0; i <= 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (less(j + 1, j)) {
                    swap(j, j + 1);
                }
            }
        }
    }

    private static void swap(final int j, final int i) {
        Integer tmp;

        tmp = index.get(i);
        index.set(i, index.get(j));
        index.set(j, tmp);
    }

    private static boolean less(int i, int j) {
        i = index.get(i);
        j = index.get(j);

        if (sums.get(i) < sums.get(j)) {
            return true;
        } else if (sums.get(i) > sums.get(j)) {
            return false;
        }

        for (int k = 0; k < n; ++k) {
            if (tos.get(i).get(k) < tos.get(j).get(k)) {
                return true;
            } else if (tos.get(i).get(k) > tos.get(j).get(k)) {
                return false;
            }
        }

        return false;
    }

    private static List<Integer> calcTo(int value) {
        List<Integer> newNum = copy(numbers);
        final int valueCount = counts.get(value);

        int countTodo = k - valueCount;
        if (countTodo > 0) {
            int sum = 0;
            for (int diff = 1; diff <= 9; ++diff) {
                int bro = value + diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }

                bro = value - diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }
            }
            sums.set(value, sum);
        } else {
            sums.set(value, 0);
        }
        return newNum;
    }

    private static void replaceFirst(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = 0; i < newNum.size() && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static int count(List<Integer> values, int targetValue) {
        int result = 0;
        for (final Integer value : values) {
            if (value.equals(targetValue)) {
                result++;
            }
        }

        return result;
    }

    private static List<Integer> copy(List<Integer> values) {
        final List<Integer> result = new ArrayList<Integer>(100);
        result.addAll(values);

        return result;
    }

    private static void doInput(final InputStream input, final Scanner scanner) {
        final List<Integer> numbersList = new ArrayList<Integer>(100);

        n = getInt(input);
        k = getInt(input);

        char first;
        while (true) {
            try {
                final char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {
            }
        }

        numbersList.add(Character.digit(first, 10));
        for (int i = 1; i < n; ++i) {
            try {
                final char c = (char)input.read();
                if (!Character.isDigit(c)) {
                    continue;
                }
                numbersList.add(Character.digit(c, 10));
            } catch (IOException ignored) {}
        }

        numbers = numbersList;
    }

    private static int getInt(final InputStream input) {
        char first;
        while (true) {
            try {
                char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {}
        }

        int result = Character.digit(first, 10);
        while (true) {
            try {
                char c = (char) input.read();
                if (!Character.isDigit(c)) {
                    break;
                }
                result = result * 10 + Character.digit(c, 10);
            } catch (IOException ignored) {}
        }

        return result;
    }

    private static void doOutput(final PrintWriter writer) {
        int ind = index.get(0);
        writer.println(sums.get(ind));
        for (final Integer value : tos.get(ind)) {
            writer.print(value);
        }
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Math.min;

public class TaskC {
    public static void main(String[] args) {
        final BufferedInputStream input = new BufferedInputStream(System.in);
        //final Scanner scanner = new Scanner(input);
        doInput(System.in, null);
        //scanner.close();

        solveTask();

        final PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
        doOutput(writer);
        writer.close();
    }

    private static int n, k;
    private static List<Integer> numbers;
    private static List<Integer> counts = new ArrayList<Integer>();
    private static final List<Integer> sums = new ArrayList<Integer>();
    private static final List<List<Integer>> tos = new ArrayList<List<Integer>>();
    private static final List<Integer> index = new ArrayList<Integer>();

    private static void solveTask() {
        counts.clear();
        for (int i = 0; i <= 9; ++i) {
            counts.add(count(numbers, i));
        }

        for (int i = 0; i <= 9; ++i) {
            index.add(i);
        }

        sums.addAll(counts);

        for (int i = 0; i <= 9; ++i) {
            tos.add(calcTo(i));
        }

        for (int i = 0; i <= 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (less(j + 1, j)) {
                    swap(j, j + 1);
                }
            }
        }
    }

    private static void swap(final int j, final int i) {
        List<Integer> tmpList;
        Integer tmp;

        tmp = index.get(i);
        index.set(i, index.get(j));
        index.set(j, tmp);
    }

    private static boolean less(int i, int j) {
        i = index.get(i);
        j = index.get(j);

        if (sums.get(i) < sums.get(j)) {
            return true;
        } else if (sums.get(i) > sums.get(j)) {
            return false;
        }

        for (int k = 0; k < n; ++k) {
            if (tos.get(i).get(k) < tos.get(j).get(k)) {
                return true;
            } else if (tos.get(i).get(k) > tos.get(j).get(k)) {
                return false;
            }
        }

        return false;
    }

    private static List<Integer> calcTo(int value) {
        List<Integer> newNum = copy(numbers);
        final int valueCount = counts.get(value);

        int countTodo = k - valueCount;
        if (countTodo > 0) {
            int sum = 0;
            for (int diff = 1; diff <= 9; ++diff) {
                int bro = value + diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }

                bro = value - diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }
            }
            sums.set(value, sum);
        } else {
            sums.set(value, 0);
        }
        return newNum;
    }

    private static void replaceFirst(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = 0; i < newNum.size() && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static int count(List<Integer> values, int targetValue) {
        int result = 0;
        for (final Integer value : values) {
            if (value.equals(targetValue)) {
                result++;
            }
        }

        return result;
    }

    private static List<Integer> copy(List<Integer> values) {
        final List<Integer> result = new ArrayList<Integer>(100);
        result.addAll(values);

        return result;
    }

    private static void doInput(final InputStream input, final Scanner scanner) {
        final List<Integer> numbersList = new ArrayList<Integer>(100);

        n = getInt(input);
        k = getInt(input);

        for (int i = 0; i < n; ++i) {
            try {
                final char c = (char)input.read();
                if (!Character.isDigit(c)) {
                    continue;
                }
                numbersList.add(Character.digit(c, 10));
            } catch (IOException ignored) {}
        }

        numbers = numbersList;
    }

    private static int getInt(final InputStream input) {
        char first;
        while (true) {
            try {
                char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {}
        }

        int result = Character.digit(first, 10);
        while (true) {
            try {
                char c = (char) input.read();
                if (!Character.isDigit(c)) {
                    break;
                }
                result = result * 10 + Character.digit(c, 10);
            } catch (IOException ignored) {}
        }

        return result;
    }

    private static void doOutput(final PrintWriter writer) {
        int ind = index.get(0);
        writer.println(sums.get(ind));
        for (final Integer value : tos.get(ind)) {
            writer.print(value);
        }
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Math.min;

public class TaskC {
    public static void main(String[] args) {
        final BufferedInputStream input = new BufferedInputStream(System.in);
        //final Scanner scanner = new Scanner(input);
        doInput(System.in, null);
        //scanner.close();

        solveTask();

        final PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
        doOutput(writer);
        writer.close();
    }

    private static int n, k;
    private static List<Integer> numbers;
    private static List<Integer> counts = new ArrayList<Integer>();
    private static final List<Integer> sums = new ArrayList<Integer>();
    private static final List<List<Integer>> tos = new ArrayList<List<Integer>>();
    private static final List<Integer> index = new ArrayList<Integer>();

    private static void solveTask() {
        counts.clear();
        for (int i = 0; i <= 9; ++i) {
            counts.add(count(numbers, i));
        }

        for (int i = 0; i <= 9; ++i) {
            index.add(i);
        }

        sums.addAll(counts);

        for (int i = 0; i <= 9; ++i) {
            tos.add(calcTo(i));
        }

        for (int i = 0; i <= 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (less(j + 1, j)) {
                    swap(j, j + 1);
                }
            }
        }
    }

    private static void swap(final int j, final int i) {
        Integer tmp;

        tmp = index.get(i);
        index.set(i, index.get(j));
        index.set(j, tmp);
    }

    private static boolean less(int i, int j) {
        i = index.get(i);
        j = index.get(j);

        if (sums.get(i) < sums.get(j)) {
            return true;
        } else if (sums.get(i) > sums.get(j)) {
            return false;
        }

        for (int k = 0; k < n; ++k) {
            if (tos.get(i).get(k) < tos.get(j).get(k)) {
                return true;
            } else if (tos.get(i).get(k) > tos.get(j).get(k)) {
                return false;
            }
        }

        return false;
    }

    private static List<Integer> calcTo(int value) {
        List<Integer> newNum = copy(numbers);
        final int valueCount = counts.get(value);

        int countTodo = k - valueCount;
        if (countTodo > 0) {
            int sum = 0;
            for (int diff = 1; diff <= 9; ++diff) {
                int bro = value + diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }

                bro = value - diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }
            }
            sums.set(value, sum);
        } else {
            sums.set(value, 0);
        }
        return newNum;
    }

    private static void replaceFirst(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = 0; i < newNum.size() && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static int count(List<Integer> values, int targetValue) {
        int result = 0;
        for (final Integer value : values) {
            if (value.equals(targetValue)) {
                result++;
            }
        }

        return result;
    }

    private static List<Integer> copy(List<Integer> values) {
        final List<Integer> result = new ArrayList<Integer>(100);
        result.addAll(values);

        return result;
    }

    private static void doInput(final InputStream input, final Scanner scanner) {
        final List<Integer> numbersList = new ArrayList<Integer>(100);

        n = getInt(input);
        k = getInt(input);

        for (int i = 0; i < n; ++i) {
            try {
                final char c = (char)input.read();
                if (!Character.isDigit(c)) {
                    continue;
                }
                numbersList.add(Character.digit(c, 10));
            } catch (IOException ignored) {}
        }

        numbers = numbersList;
    }

    private static int getInt(final InputStream input) {
        char first;
        while (true) {
            try {
                char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {}
        }

        int result = Character.digit(first, 10);
        while (true) {
            try {
                char c = (char) input.read();
                if (!Character.isDigit(c)) {
                    break;
                }
                result = result * 10 + Character.digit(c, 10);
            } catch (IOException ignored) {}
        }

        return result;
    }

    private static void doOutput(final PrintWriter writer) {
        int ind = index.get(0);
        writer.println(sums.get(ind));
        for (final Integer value : tos.get(ind)) {
            writer.print(value);
        }
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Math.min;

public class TaskC {
    public static void main(String[] args) {
        final BufferedInputStream input = new BufferedInputStream(System.in);
        //final Scanner scanner = new Scanner(input);
        doInput(System.in, null);
        //scanner.close();

        solveTask();

        final PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
        doOutput(writer);
        writer.close();
    }

    private static int n, k;
    private static List<Integer> numbers;
    private static List<Integer> counts = new ArrayList<Integer>();
    private static final List<Integer> sums = new ArrayList<Integer>();
    private static final List<List<Integer>> tos = new ArrayList<List<Integer>>();
    private static final List<Integer> index = new ArrayList<Integer>();

    private static void solveTask() {
        counts.clear();
        for (int i = 0; i <= 9; ++i) {
            counts.add(count(numbers, i));
        }

        for (int i = 0; i <= 9; ++i) {
            index.add(i);
        }

        sums.addAll(counts);

        for (int i = 0; i <= 9; ++i) {
            tos.add(calcTo(i));
        }

        for (int i = 0; i <= 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (less(j + 1, j)) {
                    swap(j, j + 1);
                }
            }
        }
    }

    private static void swap(final int j, final int i) {
        Integer tmp;

        tmp = index.get(i);
        index.set(i, index.get(j));
        index.set(j, tmp);
    }

    private static boolean less(int i, int j) {
        i = index.get(i);
        j = index.get(j);

        if (sums.get(i) < sums.get(j)) {
            return true;
        } else if (sums.get(i) > sums.get(j)) {
            return false;
        }

        for (int k = 0; k < n; ++k) {
            if (tos.get(i).get(k) < tos.get(j).get(k)) {
                return true;
            } else if (tos.get(i).get(k) > tos.get(j).get(k)) {
                return false;
            }
        }

        return false;
    }

    private static List<Integer> calcTo(int value) {
        List<Integer> newNum = copy(numbers);
        final int valueCount = counts.get(value);

        int countTodo = k - valueCount;
        if (countTodo > 0) {
            int sum = 0;
            for (int diff = 1; diff <= 9; ++diff) {
                int bro = value + diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }

                bro = value - diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceLast(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }
            }
            sums.set(value, sum);
        } else {
            sums.set(value, 0);
        }
        return newNum;
    }

    private static void replaceLast(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = newNum.size() - 1; i >= 0 && count > 0; --i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static void replaceFirst(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = 0; i < newNum.size() && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static int count(List<Integer> values, int targetValue) {
        int result = 0;
        for (final Integer value : values) {
            if (value.equals(targetValue)) {
                result++;
            }
        }

        return result;
    }

    private static List<Integer> copy(List<Integer> values) {
        final List<Integer> result = new ArrayList<Integer>(100);
        result.addAll(values);

        return result;
    }

    private static void doInput(final InputStream input, final Scanner scanner) {
        final List<Integer> numbersList = new ArrayList<Integer>(100);

        n = getInt(input);
        k = getInt(input);

        char first;
        while (true) {
            try {
                final char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {
            }
        }

        numbersList.add(Character.digit(first, 10));
        for (int i = 1; i < n; ++i) {
            try {
                final char c = (char)input.read();
                if (!Character.isDigit(c)) {
                    continue;
                }
                numbersList.add(Character.digit(c, 10));
            } catch (IOException ignored) {}
        }

        numbers = numbersList;
    }

    private static int getInt(final InputStream input) {
        char first;
        while (true) {
            try {
                char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {}
        }

        int result = Character.digit(first, 10);
        while (true) {
            try {
                char c = (char) input.read();
                if (!Character.isDigit(c)) {
                    break;
                }
                result = result * 10 + Character.digit(c, 10);
            } catch (IOException ignored) {}
        }

        return result;
    }

    private static void doOutput(final PrintWriter writer) {
        int ind = index.get(0);
        writer.println(sums.get(ind));
        for (final Integer value : tos.get(ind)) {
            writer.print(value);
        }
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Math.min;

public class TaskC {
    public static void main(String[] args) {
        final BufferedInputStream input = new BufferedInputStream(System.in);
        //final Scanner scanner = new Scanner(input);
        doInput(System.in, null);
        //scanner.close();

        solveTask();

        final PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
        doOutput(writer);
        writer.close();
    }

    private static int n, k;
    private static List<Integer> numbers;
    private static List<Integer> counts = new ArrayList<Integer>();
    private static final List<Integer> sums = new ArrayList<Integer>();
    private static final List<List<Integer>> tos = new ArrayList<List<Integer>>();
    private static final List<Integer> index = new ArrayList<Integer>();

    private static void solveTask() {
        counts.clear();
        for (int i = 0; i <= 9; ++i) {
            counts.add(count(numbers, i));
        }

        for (int i = 0; i <= 9; ++i) {
            index.add(i);
        }

        sums.addAll(counts);

        for (int i = 0; i <= 9; ++i) {
            tos.add(calcTo(i));
        }

        for (int i = 0; i <= 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (less(j + 1, j)) {
                    swap(j, j + 1);
                }
            }
        }
    }

    private static void swap(final int j, final int i) {
        Integer tmp;

        tmp = index.get(i);
        index.set(i, index.get(j));
        index.set(j, tmp);
    }

    private static boolean less(int i, int j) {
        i = index.get(i);
        j = index.get(j);

        if (sums.get(i) < sums.get(j)) {
            return true;
        } else if (sums.get(i) > sums.get(j)) {
            return false;
        }

        for (int k = 0; k < n; ++k) {
            if (tos.get(i).get(k) < tos.get(j).get(k)) {
                return true;
            } else if (tos.get(i).get(k) > tos.get(j).get(k)) {
                return false;
            }
        }

        return false;
    }

    private static List<Integer> calcTo(int value) {
        List<Integer> newNum = copy(numbers);
        final int valueCount = counts.get(value);

        int countTodo = k - valueCount;
        if (countTodo > 0) {
            int sum = 0;
            for (int diff = 1; diff <= 9; ++diff) {
                int bro = value + diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceFirst(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }

                bro = value - diff;
                if (bro >= 0 && bro <= 9) {
                    final int toReplace = min(counts.get(bro), countTodo);
                    replaceLast(newNum, bro, value, toReplace);
                    countTodo -= toReplace;
                    sum += diff * toReplace;
                }
            }
            sums.set(value, sum);
        } else {
            sums.set(value, 0);
        }
        return newNum;
    }

    private static void replaceLast(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = newNum.size() - 1; i >= 0 && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static void replaceFirst(final List<Integer> newNum, final int src, final int dst,
          int count) {
        for (int i = 0; i < newNum.size() && count > 0; ++i) {
            if (newNum.get(i).equals(src)) {
                newNum.set(i, dst);
                count--;
            }
        }
    }

    private static int count(List<Integer> values, int targetValue) {
        int result = 0;
        for (final Integer value : values) {
            if (value.equals(targetValue)) {
                result++;
            }
        }

        return result;
    }

    private static List<Integer> copy(List<Integer> values) {
        final List<Integer> result = new ArrayList<Integer>(100);
        result.addAll(values);

        return result;
    }

    private static void doInput(final InputStream input, final Scanner scanner) {
        final List<Integer> numbersList = new ArrayList<Integer>(100);

        n = getInt(input);
        k = getInt(input);

        char first;
        while (true) {
            try {
                final char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {
            }
        }

        numbersList.add(Character.digit(first, 10));
        for (int i = 1; i < n; ++i) {
            try {
                final char c = (char)input.read();
                if (!Character.isDigit(c)) {
                    continue;
                }
                numbersList.add(Character.digit(c, 10));
            } catch (IOException ignored) {}
        }

        numbers = numbersList;
    }

    private static int getInt(final InputStream input) {
        char first;
        while (true) {
            try {
                char c = (char) input.read();
                if (Character.isDigit(c)) {
                    first = c;
                    break;
                }
            } catch (IOException ignored) {}
        }

        int result = Character.digit(first, 10);
        while (true) {
            try {
                char c = (char) input.read();
                if (!Character.isDigit(c)) {
                    break;
                }
                result = result * 10 + Character.digit(c, 10);
            } catch (IOException ignored) {}
        }

        return result;
    }

    private static void doOutput(final PrintWriter writer) {
        int ind = index.get(0);
        writer.println(sums.get(ind));
        for (final Integer value : tos.get(ind)) {
            writer.print(value);
        }
    }
}


#include <bits/stdc++.h>
#define For(i,a,b) for ( int i=(a);i<=(b);i++ )
#define Dow(i,b,a) for ( int i=(b);i>=(a);i-- )
#define GO(i,x) for ( int i=head[x];~i;i=e[i].nex )
#define mem(x,s) memset(x,s,sizeof(x))
#define cpy(x,s) memcpy(x,s,sizeof(x))
#define YES return puts("YES"),0
#define NO return puts("NO"),0
#define GG return puts("-1"),0
#define pb push_back
using namespace std;

struct IO
{
	#define MAXSIZE (1 << 20)
	#define isdigit(x) (x >= '0' && x <= '9')
  	char buf[MAXSIZE],*p1,*p2;
  	char pbuf[MAXSIZE],*pp;
  	IO():p1(buf),p2(buf),pp(pbuf){}
  	inline char gc() {
//  		return getchar();
    	if (p1==p2) p2=(p1=buf)+fread(buf,1,MAXSIZE,stdin);
    	return p1==p2?' ':*p1++;
  	}
	inline bool blank(char ch) {return ch==' '||ch =='\n'||ch == '\r'||ch == '\t';}
  	template <class T>
  	inline void read(T &x)
	{
	    register double tmp=1;register bool sign=0; x=0;
	    register char ch=gc();
	    for (;!isdigit(ch);ch=gc()) if(ch=='-') sign=1;
	    for (;isdigit(ch);ch=gc()) x=x*10+(ch-'0');
	    if (ch=='.') for (ch=gc();isdigit(ch);ch=gc()) tmp/=10.0,x+=tmp*(ch-'0');
	    if (sign) x=-x;
  	}
  	inline void read(char *s)
	{
    	register char ch=gc();
		for (;blank(ch);ch=gc());
		for (;!blank(ch);ch=gc()) *s++=ch;
    	*s=0;
  	}
  	inline void read(char &c) {for(c=gc();blank(c);c=gc());}
  	template<class t> inline void write(t x){
		if(x<0) putchar('-'),write(-x);
		else{if(x>9) write(x/10);putchar('0'+x%10);}
	}
} io;

const int mod=1e9+7;
const int mo=998244353;
const int N=3e5+5;

int n,m,Q,laz[N],gs[N],qx[N],qy[N],op[N],qz[N],ans[N],head[N],cnt,sxm;

struct Node
{
	int nex,to;
};
Node e[N<<1];

inline void jia(int u,int v)
{
	e[++cnt].nex=head[u];
	head[u]=cnt;
	e[cnt].to=v;
}

map<int,map<int,int> >Mp;

inline void dfs(int u)
{
	int hh=0;
	if(op[u]==1&&!(Mp[qx[u]][qy[u]]^laz[qx[u]]))
	{
		hh=1;
		sxm++;
		Mp[qx[u]][qy[u]]=laz[qx[u]]^1;
		gs[qx[u]]++;
	}
	if(op[u]==2&&(Mp[qx[u]][qy[u]]^laz[qx[u]]))
	{
		hh=1;
		sxm--;
		Mp[qx[u]][qy[u]]=laz[qx[u]];
		gs[qx[u]]--;
	}
	if(op[u]==3)
	{
		hh=1;
		sxm=sxm-gs[qz[u]]+m-gs[qz[u]];
		gs[qz[u]]=m-gs[qz[u]];
		laz[qz[u]]^=1;
	}
	ans[u]=sxm;
	GO(i,u) dfs(e[i].to);

	if(!hh) return;
	if(op[u]==1)
	{
		sxm--;
		Mp[qx[u]][qy[u]]=laz[qx[u]];
		gs[qx[u]]--;
	}
	if(op[u]==2)
	{
		sxm++;
		Mp[qx[u]][qy[u]]=laz[qx[u]]^1;
		gs[qx[u]]++;
	}
	if(op[u]==3)
	{
		sxm=sxm-gs[qz[u]]+m-gs[qz[u]];
		gs[qz[u]]=m-gs[qz[u]];
		laz[qz[u]]^=1;
	}
}

int main()
{
	io.read(n),io.read(m),io.read(Q);
	mem(head,-1);
	jia(0,1);
	For(i,1,Q)
	{
		int type; io.read(type);
		op[i]=type;
		if(type<3) io.read(qx[i]),io.read(qy[i]);
		else io.read(qz[i]);
	}
	Dow(i,Q,1)
	{
		if(op[i]==4) jia(qz[i],i);
		if(op[i+1]!=4&&i<Q) jia(i,i+1);
	}
	GO(i,0) dfs(e[i].to);
	For(i,1,Q) io.write(ans[i]),puts("");
	return 0;
}
/*
2 3 9
1 1 1
1 1 1
2 1 1
2 1 1
3 2
3 2
4 0
4 7
4 5
*/


#include<bits/stdc++.h>
using namespace std;
const int N=1e3+5;
const int Q=1e5+5;
int n,mm,q;
int opt[Q],x[Q],y[Q],ans[Q],cnt;
bitset<N> m[N],all;//因为全部都是01子串，所以说用bitset更方便
int tot,head[Q],nxt[Q],to[Q];
void add(int x,int y){
	nxt[++tot]=head[x];to[tot]=y;head[x]=tot;
}
void dfs(int pos){//pos是时间点
	bool f=0;
	if(opt[pos]==1&&m[x[pos]][y[pos]]==0){cnt++;f=1;m[x[pos]][y[pos]]=1;}
	if(opt[pos]==2&&m[x[pos]][y[pos]]==1){cnt--;f=1;m[x[pos]][y[pos]]=0;}
	if(opt[pos]==3&&m[x[pos]][y[pos]]==0){f=1;cnt-=m[x[pos]].count();m[x[pos]]^=all;cnt+=m[x[pos]].count();}
	ans[pos]=cnt;
	for(int i=head[pos];i;i=nxt[i]) dfs(to[i]);
	if(f){//回溯操作，还原图
		if(opt[pos]==1){cnt--;m[x[pos]][y[pos]]=0;}
		if(opt[pos]==2){cnt++;m[x[pos]][y[pos]]=1;}
		if(opt[pos]==3){cnt-=m[x[pos]].count();m[x[pos]]^=all;cnt+=m[x[pos]].count();}
	}
}
int main(){
	cin>>n>>mm>>q;
	for(int i=1;i<=mm;i++) all.set(i);
	for(int i=1;i<=q;i++){
		scanf("%d%d",&opt[i],&x[i]);
		if(opt[i]==4) add(x[i],i);//将操作之间连边，方便直接跳转
		else{
			if(opt[i]<3){
			scanf("%d",&y[i]);}
			add(i-1,i);
		}
	}
	dfs(0);
	for(int i=1;i<=q;i++) printf("%d\n",ans[i]);
	return 0;
}


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
#define f(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
int n,m,q;// ��������Ĵ�С�Լ�ָ�������
const int MAXN=1e3+5,MAXP=1e5+5;
int now,ans,cc;
bool d[MAXN][MAXN]={0};//0�� 1վ
int change[MAXP][2]={0};//i��j��ʾ����˱������� i 0��ʾ��һ�б������� 0 0��0 j��ʾû�в���
int M[MAXP]={0};
inline int  A (int i,int j)
{
	now++;
	if(d[i][j]==0)
	{
		d[i][j]=1;
		ans++;
		change[now][0]=i;
		change[now][1]=j;
		M[now]=ans;
		return ans;
	}
	else
	{
		change[now][0]=0;
		change[now][1]=0;
		M[now]=ans;
		return ans;
	}
}
inline int  B (int i,int j)
{
	now++;
	if(d[i][j]==1)
	{
		d[i][j]=0;
		ans--;
		change[now][0]=i;
		change[now][1]=j;
		M[now]=ans;
		return ans;
	}
	else
	{
		change[now][0]=0;
		change[now][1]=0;
		M[now]=ans;
		return ans;
	}
}
inline int  C (int i)
{
	now++;
	change[now][0]=i;
	f(j,1,m)
	{
	if(d[i][j]==0)
	{
		d[i][j]=1;
		ans++;
	}
	else
	{
		d[i][j]=0;
		ans--;
	}
    }
    M[now]=ans;
    return ans;
}
inline int  D (int k)
{
	now++;
    cc+=now-k;
    fd(i,k-cc,now-cc-1)
    {
    	if(change[i][0]==0) continue;
    	else{
    		if (change[i][1]==0)
    		{
    				f(j,1,m)
	{
	if(d[i][j]==0)
	{
		d[i][j]=1;
	}
	else
	{
		d[i][j]=0;
	}
    }
			}
			else{
				if(d[change[i][0]][change[i][1]]==0)d[change[i][0]][change[i][1]]=1;
				else d[change[i][0]][change[i][1]]=0;

			}
		}
    }
    ans=M[k];
    M[now]=ans;
    return ans;

}

int main()
{
	//freopen("elder.in","r",stdin);
	//freopen("elder.out","w",stdout);
	cin>>n>>m>>q;
	f(i,1,q)
	{
		int opt;
		scanf("%d",&opt);
		if(opt==1)
		{
			int i,j;
			cin>>i>>j;
			cout<<A(i,j)<<endl;
		}
		if(opt==2)
		{
			int i,j;
			cin>>i>>j;
			cout<<B(i,j)<<endl;
		}
		if(opt==3)
		{
			int i;
			cin>>i;
			cout<<C(i)<<endl;
		}
		if(opt==4)
		{
			int k;
			cin>>k;
			cout<<D(k)<<endl;
		}
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N=3e5+5;
int n,m,q;
int f[N],tag[N],sum[N],id[N];
set<int>s[N];
struct number{int opt,x,y;}num[N];
int cnt,head[N];
struct edge{int next,from,to;}e[N<<1];

inline void add(int u,int v)
{
	cnt++;
	e[cnt].next=head[u];
	e[cnt].from=u;
	e[cnt].to=v;
	head[u]=cnt;
}

void dfs(int u,int ans)
{
	int x=num[u].x,y=num[u].y,last;
	if (num[u].opt==1)
	{
		if (tag[x]==0)
		{
			if (s[x].find(y)==s[x].end())
			{
				id[u]=1;
				s[x].insert(y);
				ans++;
			}
		}
		else
		{
			if (s[x].find(y)!=s[x].end())
			{
				id[u]=2;
				s[x].erase(y);
				ans++;
			}
		}
	}
	if (num[u].opt==2)
	{
		if (tag[x]==0)
		{
			if (s[x].find(y)!=s[x].end())
			{
				id[u]=3;
				s[x].erase(y);
				ans--;
			}
		}
		else
		{
			if (s[x].find(y)==s[x].end())
			{
				id[u]=4;
				s[x].insert(y);
				ans--;
			}
		}
	}
	if (num[u].opt==3)
	{
		if (tag[x]==0)
		{
			id[u]=5;
			tag[x]^=1;
			ans=ans-s[x].size()+m-s[x].size();
		}
		else
		{
			id[u]=6;
			tag[x]^=1;
			ans=ans-(m-s[x].size())+s[x].size();
		}
	}
	f[u]=ans;
	for (register int i=head[u]; i; i=e[i].next) dfs(e[i].to,ans);
	if (id[u]==1)
	{
		s[x].erase(y);
		ans--;
	}
	if (id[u]==2)
	{
		s[x].insert(y);
		ans--;
	}
	if (id[u]==3)
	{
		s[x].insert(y);
		ans++;
	}
	if (id[u]==4)
	{
		s[x].erase(y);
		ans++;
	}
	if (id[u]==5)
	{
		tag[x]^=1;
		ans=ans-(m-s[x].size())+s[x].size();
	}
	if (id[u]==6)
	{
		tag[x]^=1;
		ans=ans-s[x].size()+m-s[x].size();
	}
}

int main(){

	scanf("%d%d%d",&n,&m,&q);
	for (register int i=1; i<=q; ++i)
	{
		scanf("%d",&num[i].opt);
		if (num[i].opt<=2) scanf("%d%d",&num[i].x,&num[i].y);
		else scanf("%d",&num[i].x);
	}
	for (register int i=1; i<=q; ++i)
	{
		if (num[i].opt==4) add(num[i].x,i);
		else add(i-1,i);
	}
	dfs(0,0);
	for (register int i=1; i<=q; ++i) printf("%d\n",f[i]);
return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int n,m,q,s,edgenum,head[N],Next[N],vet[N],res[N],opt[N],x[N],y[N];
bitset<1005>mat[1005],ch;
void add(int u,int v){
	edgenum++;
	Next[edgenum]=head[u];
	vet[edgenum]=v;
	head[u]=edgenum;
}
void dfs(int u){
	bool flag=0;
	if(opt[u]==1&&mat[x[u]][y[u]]==0){
		s++,flag=1;
		mat[x[u]][y[u]]=1;
	}
	if(opt[u]==2&&mat[x[u]][y[u]]==1){
		s--,flag=1;
		mat[x[u]][y[u]]=0;
	}
	if(opt[u]==3){
		flag=1;
		s-=mat[x[u]].count();
		mat[x[u]]^=ch;
		s+=mat[x[u]].count();
	}
	res[u]=s;
	for(int e=head[u];e;e=Next[e]){
		int v=vet[e];
		dfs(v);
	}
	if(!flag)return;
	if(opt[u]==1){
		s--;
		mat[x[u]][y[u]]=0;
	}
	if(opt[u]==2){
		s++;
		mat[x[u]][y[u]]=1;
	}
	if(opt[u]==3){
		s-=mat[x[u]].count();
		mat[x[u]]^=ch;
		s+=mat[x[u]].count();
	}
}
int main(){
	scanf("%d%d%d",&n,&m,&q);
	for(int i=1;i<=m;i++)ch.set(i,1);
	for(int i=1;i<=q;i++){
		scanf("%d%d",&opt[i],&x[i]);
		if(opt[i]<=2)scanf("%d",&y[i]);
		if(opt[i]==4)add(x[i],i);
		else add(i-1,i);
	}
	dfs(0);
	for(int i=1;i<=q;i++)
		printf("%d\n",res[i]);
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#define Q 100010
#define N 1010

int n, m, q, tot;
int vis[N][N], head[Q], ans[Q];
struct OP {
	int op, a, b;
}opt[Q];

struct edge {
	int next, v;
}e[Q];

void add(int u, int v) {
	e[++tot].v = v;
	e[tot].next = head[u];
	head[u] = tot;
}

void dfs(int x, int sum) {

	int op = opt[x].op, i = opt[x].a, j = opt[x].b, flag = 0;

	if (op == 1 && !vis[i][j]) { vis[i][j] = 1; ++sum; flag = 1; }
	if (op == 2 && vis[i][j]) { vis[i][j] = 0; --sum; flag = 1; }
	if (op == 3) {
		for (int jj = 1; jj <= m; jj++)
			if (vis[i][jj]) {
				--sum;
				vis[i][jj] = 0;
			}
			else {
				vis[i][jj] = 1;
				++sum;
			}
		flag = 1;
	}

	ans[x] = sum;
	for (i = head[x]; i; i = e[i].next)
		dfs(e[i].v, sum);

	i = opt[x].a;

	if (op == 1 && flag == 1)
		vis[i][j] = 0;

	if (op == 2 && flag == 1)
		vis[i][j] = 1;

	if (op == 3 && flag == 1) {
		for (int jj = 1; jj <= m; jj++)
			if (vis[i][jj])
				vis[i][jj] = 0;
			else
				vis[i][jj] = 1;
	}
	return;
}

int main() {

	//freopen("elder1.in", "r", stdin);

	scanf("%d%d%d", &n, &m, &q);
	for (int i = 1; i <= q; i++) {
		scanf("%d%d", &opt[i].op, &opt[i].a);
		if (opt[i].op <= 2)
			scanf("%d", &opt[i].b);
		if (opt[i].op <= 3) {
			add(i - 1, i);
		}
		else
			add(opt[i].a, i);
	}

	/*
	for (int u = 1; u <= n; u++) {
		for (int i = head[u]; i; i = e[i].next) {
			printf("%d  %d\n", u, e[i].v);
		}
	}*/

	dfs(0, 0);

	for (int i = 1; i <= q; i++)
		printf("%d\n", ans[i]);

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#define Q 100010
#define N 1010

int n, m, q, tot;
int vis[N][N], head[Q], ans[Q];
struct OP {
	int op, a, b;
}opt[Q];

struct edge {
	int next, v;
}e[Q];

void add(int u, int v) {
	e[++tot].v = v;
	e[tot].next = head[u];
	head[u] = tot;
}

void dfs(int x, int sum) {

	int op = opt[x].op, i = opt[x].a, j = opt[x].b, flag = 0;

	if (op == 1 && !vis[i][j]) { vis[i][j] = 1; ++sum; flag = 1; }
	if (op == 2 && vis[i][j]) { vis[i][j] = 0; --sum; flag = 1; }
	if (op == 3) {
		for (int jj = 1; jj <= m; jj++)
			if (vis[i][jj]) {
				--sum;
				vis[i][jj] = 0;
			}
			else {
				vis[i][jj] = 1;
				++sum;
			}
		flag = 1;
	}

	ans[x] = sum;
	for (i = head[x]; i; i = e[i].next)
		dfs(e[i].v, sum);

	i = opt[x].a;

	if (op == 1 && flag == 1)
		vis[i][j] = 0;

	if (op == 2 && flag == 1)
		vis[i][j] = 1;

	if (op == 3 && flag == 1) {
		for (int jj = 1; jj <= m; jj++)
			if (vis[i][jj])
				vis[i][jj] = 0;
			else
				vis[i][jj] = 1;
	}
	return;
}

int main() {

	freopen("elder1.in", "r", stdin);

	scanf("%d%d%d", &n, &m, &q);
	for (int i = 1; i <= q; i++) {
		scanf("%d%d", &opt[i].op, &opt[i].a);
		if (opt[i].op <= 2)
			scanf("%d", &opt[i].b);
		if (opt[i].op <= 3) {
			add(i - 1, i);
		}
		else
			add(opt[i].a, i);
	}

	/*
	for (int u = 1; u <= n; u++) {
		for (int i = head[u]; i; i = e[i].next) {
			printf("%d  %d\n", u, e[i].v);
		}
	}*/

	dfs(0, 0);

	for (int i = 1; i <= q; i++)
		printf("%d\n", ans[i]);

	return 0;
}


#include<cstdio>
#include<bitset>
using namespace std;
const int maxn=1010;
const int maxq=1e5+10;
int n,m,q;
int ans[maxq],opt[maxq],x[maxq],y[maxq],cnt;
bitset<maxn> map[maxn],all_one;
int tot,head[maxq],nxt[maxq],to[maxq];
void add(int x,int y)
{
    to[++tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
void dfs(int pos)
{
    bool flag=0;
    if(opt[pos]==1 && map[x[pos]][y[pos]]==0)
    {
        flag=1;
        map[x[pos]][y[pos]]=1;
        cnt++;
    }
    if(opt[pos]==2 && map[x[pos]][y[pos]]==1)
    {
        flag=1;
        map[x[pos]][y[pos]]=0;
        cnt--;
    }
    if(opt[pos]==3)
    {
        flag=1;
        cnt-=map[x[pos]].count();
        map[x[pos]]^=all_one;
        cnt+=map[x[pos]].count();
    }
    ans[pos]=cnt;
    for(int i=head[pos];i;i=nxt[i])
        dfs(to[i]);
    if(flag)
    {
        if(opt[pos]==1)
            cnt--,map[x[pos]][y[pos]]=0;
        if(opt[pos]==2)
            cnt++,map[x[pos]][y[pos]]=1;
        if(opt[pos]==3)
        {
            cnt-=map[x[pos]].count();
            map[x[pos]]^=all_one;
            cnt+=map[x[pos]].count();
        }
    }
}
int main()
{
    scanf("%d%d%d",&n,&m,&q);
    for(int i=1;i<=m;i++)
        all_one.set(i);
    for(int i=1;i<=q;i++)
    {
        scanf("%d%d",&opt[i],&x[i]);
        if(opt[i]==4)
            add(x[i],i);
        else
            if(opt[i]<3)
                scanf("%d",&y[i]);
        if(opt[i]<4)
            add(i-1,i);
    }
    dfs(0);
    for(int i=1;i<=q;i++)
        printf("%d\n",ans[i]);
    return 0;
}


#include<iostream>
#include<cstdio>
using namespace std;
int a[10005][10005];
int n,m,q;
int num,i,j,k;
int cnt[1000005];
void test(){
	for(int x=1;x<=n;x++){
		for(int y=1;y<=m;y++){
			cout<<a[x][y]<<" ";
		}
		cout<<endl;
	}
}
void ij1(){
	cin>>i>>j;
	if(a[i][j]==0){
		a[i][j]=1;
	}
}
void ij2(){
	cin>>i>>j;
	if(a[i][j]==1){
		a[i][j]=0;
    }
}
void i3(){
	cin>>i;
	for(int x=1;x<=m;x++){
		if(a[i][x]==1){
			a[i][x]=0;
		}else{
			a[i][x]=1;
		}
	}
}
void k4(){
	cin>>k;
	cout<<cnt[k]<<endl;
}

int main(){
	freopen("elder3.in","r",stdin);
	freopen("elder.out","w",stdout);
	cin>>n>>m>>q;
	cnt[0]=0;
	for(int x=1;x<=n;x++){
		for(int y=1;y<=m;y++){
			a[i][j]=0;
		}
	}
	for(int z=1;z<=q;z++){
		cin>>num;
		if(num==1){
			ij1();
		}else if(num==2){
			ij2();
		}else if(num==3){
			i3();
		}else{
			k4();
			continue;
		}
		for(int b=1;b<=n;b++){
			for(int c=1;c<=m;c++){
				if(a[b][c]==1){
					cnt[z]++;
				}
			}
		}
		cout<<cnt[z]<<endl;
	}
	fclose(stdin);
    fclose(stdout);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;

int sh[1005][1005];
int flag[1005];
int sum[1005];
int all;
int vis[MAXN];
vector<int> mp[MAXN];
int n,m,q;

struct Node{
	int ty; int x,y; int ans;
}as[MAXN];

int cc = 0;
void dfs(int po) {
	if(q == 70888) printf("%d\n",po);
    if(q == 70888 && cc > 100) return;
    cc ++;
	int x1,x2; int y1,y2,y3,y4; // sh[x1][x2], all, sum[x1], flag[x1]
	for(int i = 0; i < (int)mp[po].size(); ++i) {
		int tt = mp[po][i];
	  //  assert(tt > 0 && tt <= q);
		int t1 = as[tt].ty; int t2 = as[tt].x; int t3 = as[tt].y;
		x1 = t2; x2 = t3; y1 = sh[x1][x2]; y2 = all; y3 = sum[x1]; y4 = flag[x1];

		if(t1 == 1) {
			if( (flag[t2] ^ sh[t2][t3]) == 0) {
				all ++; sh[t2][t3] ^= 1; sum[t2] ++;
			}
		}else if(t1 == 2) {
			if( (flag[t2] ^ sh[t2][t3]) == 1){
				all--; sh[t2][t3] ^= 1; sum[t2] --;
			}
		}else if(t1 == 3) {
			flag[t2] ^= 1;
			all += m-sum[t2]*2;
		   	sum[t2] = m-sum[t2];
		}

		as[tt].ans = all;
		dfs(tt);

		sh[x1][x2] = y1; all = y2; sum[x1] = y3; flag[x1] = y4;
	}
}
int main(){
	while(~scanf("%d %d %d",&n,&m,&q)){
		memset(flag,0,sizeof(flag));
		memset(sh,0,sizeof(sh));
		memset(sum,0,sizeof(sum));
		all = 0;
		cc = 0;

		for(int i = 0; i <= q; ++i) mp[i].clear();

		for(int i = 1; i <= q; ++i) {
			as[i].y = 0;
			scanf("%d",&as[i].ty);
			if(as[i].ty < 3) scanf("%d %d",&as[i].x,&as[i].y);
			else scanf("%d",&as[i].x);

			if(as[i].ty == 4) mp[as[i].x].push_back(i);
			else mp[i-1].push_back(i);
		}

		dfs(0);
		for(int i = 1; i <= q; ++i) printf("%d\n",as[i].ans);
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;

int sh[1005][1005];
int flag[1005];
int sum[1005];
int all;
int vis[MAXN];
vector<int> mp[MAXN];
int n,m,q;

struct Node{
	int ty; int x,y; int ans;
}as[MAXN];

int cc = 0;
const int Ed = 25;
void dfs(int po,int fa) {
	int fl = 0;
	if(cc <INF) cc ++;
	if(q == 70888 && cc <= Ed) {
	//	printf("%dhhaa: %d fa:%d\n",cc,po,fa);
		if(po > 100) fl = 1; }
    if(q == 70888 && cc > Ed) return;

	int x1,x2; int y1,y2,y3,y4; // sh[x1][x2], all, sum[x1], flag[x1]
	for(int i = 0; i < (int)mp[po].size(); ++i) {
		int tt = mp[po][i];
	  //  assert(tt > 0 && tt <= q);
		int t1 = as[tt].ty; int t2 = as[tt].x; int t3 = as[tt].y;

		x1 = t2; x2 = t3; y1 = sh[x1][x2]; y2 = all; y3 = sum[x1]; y4 = flag[x1];

		if(fl) printf("%d:%d %d %d %d %d %d %d\n",po,tt,x1,x2,y1,y2,y3,y4);

		if(t1 == 1) {
			if( (flag[t2] ^ sh[t2][t3]) == 0) {
				all ++; sh[t2][t3] ^= 1; sum[t2] ++;
			}
		}else if(t1 == 2) {
			if( (flag[t2] ^ sh[t2][t3]) == 1){
				all--; sh[t2][t3] ^= 1; sum[t2] --;
			}
		}else if(t1 == 3) {
			flag[t2] ^= 1;
			all += m-sum[t2]*2;
		   	sum[t2] = m-sum[t2];
		}

		as[tt].ans = all;
		dfs(tt,po);

		sh[x1][x2] = y1; all = y2; sum[x1] = y3; flag[x1] = y4;
	}
}
int main(){
	while(~scanf("%d %d %d",&n,&m,&q)){
		memset(flag,0,sizeof(flag));
		memset(sh,0,sizeof(sh));
		memset(sum,0,sizeof(sum));
		all = 0;
		cc = 0;

		for(int i = 0; i <= q; ++i) mp[i].clear();

		for(int i = 1; i <= q; ++i) {
			as[i].y = 0;
			scanf("%d",&as[i].ty);
			if(as[i].ty < 3) scanf("%d %d",&as[i].x,&as[i].y);
			else scanf("%d",&as[i].x);

			if(as[i].ty == 4) mp[as[i].x].push_back(i);
			else mp[i-1].push_back(i);
		}

		dfs(0,-1);
		for(int i = 1; i <= q; ++i) printf("%d\n",as[i].ans);
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;

int sh[1005][1005];
int flag[1005];
int sum[1005];
int all;
int vis[MAXN];
vector<int> mp[MAXN];
int n,m,q;

struct Node{
	int ty; int x,y; int ans;
}as[MAXN];

int cc = 0;
const int Ed = 26;
void dfs(int po,int fa) {
	int fl = 0;
	if(cc <INF) cc ++;
	if(q == 70888 && cc <= Ed) {
	//	printf("%dhhaa: %d fa:%d\n",cc,po,fa);
		if(cc == 26) fl = 1;
	}
    if(q == 70888 && cc > Ed) return;

	int x1,x2; int y1,y2,y3,y4; // sh[x1][x2], all, sum[x1], flag[x1]
	for(int i = 0; i < (int)mp[po].size(); ++i) {
		int tt = mp[po][i];
		if(fl) { printf("%d\n",tt); continue; }
	  //  assert(tt > 0 && tt <= q);
		int t1 = as[tt].ty; int t2 = as[tt].x; int t3 = as[tt].y;

		x1 = t2; x2 = t3; y1 = sh[x1][x2]; y2 = all; y3 = sum[x1]; y4 = flag[x1];

		if(fl) { printf("%d:%d %d %d %d %d %d %d\n",po,tt,x1,x2,y1,y2,y3,y4); continue; }

		if(t1 == 1) {
			if( (flag[t2] ^ sh[t2][t3]) == 0) {
				all ++; sh[t2][t3] ^= 1; sum[t2] ++;
			}
		}else if(t1 == 2) {
			if( (flag[t2] ^ sh[t2][t3]) == 1){
				all--; sh[t2][t3] ^= 1; sum[t2] --;
			}
		}else if(t1 == 3) {
			flag[t2] ^= 1;
			all += m-sum[t2]*2;
		   	sum[t2] = m-sum[t2];
		}

		as[tt].ans = all;
		dfs(tt,po);

		sh[x1][x2] = y1; all = y2; sum[x1] = y3; flag[x1] = y4;
	}
}
int main(){
	while(~scanf("%d %d %d",&n,&m,&q)){
		memset(flag,0,sizeof(flag));
		memset(sh,0,sizeof(sh));
		memset(sum,0,sizeof(sum));
		all = 0;
		cc = 0;

		for(int i = 0; i <= q; ++i) mp[i].clear();

		for(int i = 1; i <= q; ++i) {
			as[i].y = 0;
			scanf("%d",&as[i].ty);
			if(as[i].ty < 3) scanf("%d %d",&as[i].x,&as[i].y);
			else scanf("%d",&as[i].x);

			if(as[i].ty == 4) mp[as[i].x].push_back(i);
			else mp[i-1].push_back(i);
		}

		dfs(0,-1);
		for(int i = 1; i <= q; ++i) printf("%d\n",as[i].ans);
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;

int sh[1005][1005];
int flag[1005];
int sum[1005];
int all;
int vis[MAXN];
vector<int> mp[MAXN];
int n,m,q;

struct Node{
	int ty; int x,y; int ans;
}as[MAXN];

int cc = 0;
const int Ed = 23;
void dfs(int po,int fa) {
	if(cc <INF) cc ++;
	if(q == 70888 && cc <= Ed) printf("%dhhaa: %d fa:%d\n",cc,po,fa);
    if(q == 70888 && cc > Ed) return;

	int x1,x2; int y1,y2,y3,y4; // sh[x1][x2], all, sum[x1], flag[x1]
	for(int i = 0; i < (int)mp[po].size(); ++i) {
		int tt = mp[po][i];
	  //  assert(tt > 0 && tt <= q);
		int t1 = as[tt].ty; int t2 = as[tt].x; int t3 = as[tt].y;
		x1 = t2; x2 = t3; y1 = sh[x1][x2]; y2 = all; y3 = sum[x1]; y4 = flag[x1];

		if(t1 == 1) {
			if( (flag[t2] ^ sh[t2][t3]) == 0) {
				all ++; sh[t2][t3] ^= 1; sum[t2] ++;
			}
		}else if(t1 == 2) {
			if( (flag[t2] ^ sh[t2][t3]) == 1){
				all--; sh[t2][t3] ^= 1; sum[t2] --;
			}
		}else if(t1 == 3) {
			flag[t2] ^= 1;
			all += m-sum[t2]*2;
		   	sum[t2] = m-sum[t2];
		}

		as[tt].ans = all;
		dfs(tt,po);

		sh[x1][x2] = y1; all = y2; sum[x1] = y3; flag[x1] = y4;
	}
}
int main(){
	while(~scanf("%d %d %d",&n,&m,&q)){
		memset(flag,0,sizeof(flag));
		memset(sh,0,sizeof(sh));
		memset(sum,0,sizeof(sum));
		all = 0;
		cc = 0;

		for(int i = 0; i <= q; ++i) mp[i].clear();

		for(int i = 1; i <= q; ++i) {
			as[i].y = 0;
			scanf("%d",&as[i].ty);
			if(as[i].ty < 3) scanf("%d %d",&as[i].x,&as[i].y);
			else scanf("%d",&as[i].x);

			if(as[i].ty == 4) mp[as[i].x].push_back(i);
			else mp[i-1].push_back(i);
		}

		dfs(0,-1);
		for(int i = 1; i <= q; ++i) printf("%d\n",as[i].ans);
	}
	return 0;
}