import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;

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

	private void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int[] ans = new int[N];
		for (int i = 0; i < M; i++) {
			int s = sc.nextInt() - 1;
			int c = sc.nextInt();
			if (ans[s] != 0 && ans[s] != c) {
				System.out.println(-1);
				return;
			}
			if (s == 0 && c == 0 && N > 1) {
				System.out.println(-1);
				return;
			}
			ans[s] = c;
		}
		if (N == 1) {
			System.out.println(ans[0]);
			return;
		}
		System.out.print(ans[0] == 0 ? 1 : ans[0]);
		for (int i = 1; i < N; i++) {
			System.out.print(ans[i]);
		}
		System.out.println();
	}

	class Scanner {
		private InputStream in;
		private byte[] buffer = new byte[1024];
		private int index;
		private int length;

		public Scanner(InputStream in) {
			this.in = in;
		}

		private boolean isPrintableChar(int c) {
			return '!' <= c && c <= '~';
		}

		private boolean isDigit(int c) {
			return '0' <= c && c <= '9';
		}

		private boolean hasNextByte() {
			if (index < length) {
				return true;
			} else {
				try {
					length = in.read(buffer);
					index = 0;
				} catch (IOException e) {
					e.printStackTrace();
				}
				return length > 0;
			}
		}

		private boolean hasNext() {
			while (hasNextByte() && !isPrintableChar(buffer[index])) {
				index++;
			}
			return hasNextByte();
		}

		private int readByte() {
			return hasNextByte() ? buffer[index++] : -1;
		}

		public String next() {
			if (!hasNext()) {
				throw new RuntimeException("no input");
			}
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (isPrintableChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		public long nextLong() {
			if (!hasNext()) {
				throw new RuntimeException("no input");
			}
			long value = 0L;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			while (isPrintableChar(b)) {
				if (isDigit(b)) {
					value = value * 10 + (b - '0');
				}
				b = readByte();
			}
			return minus ? -value : value;
		}

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

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

	interface CombCalculator {
		long comb(int n, int m);
	}

	interface MobiusFunction {
		int get(int n);
	}

	/**
	 * メビウス関数をエラトステネスの篩っぽく前計算するクラスです。
	 * 計算量はO(1)で、前計算でO(N logN)です。
	 */
	class SieveMobiusFunction implements MobiusFunction {
		int size;
		int[] mobiusFunctionValues;

		public SieveMobiusFunction(int size) {
			this.size = size;
			mobiusFunctionValues = new int[size];

			mobiusFunctionValues[0] = 0;
			mobiusFunctionValues[1] = 1;
			for (int i = 2; i < size; i++) {
				mobiusFunctionValues[i] = 1;
			}
			for (int i = 2; i * i < size; i++) {
				for (int k = 1; i * i * k < size; k++) {
					mobiusFunctionValues[i * i * k] *= 0;
				}
			}

			for (int i = 2; i < size; i++) {
				if (mobiusFunctionValues[i] == 1) {
					for (int k = 1; i * k < size; k++) {
						mobiusFunctionValues[i * k] *= -2;
					}
				}
				if (mobiusFunctionValues[i] > 1) {
					mobiusFunctionValues[i] = 1;
				}
				if (mobiusFunctionValues[i] < -1) {
					mobiusFunctionValues[i] = -1;
				}
			}
		}

		@Override
		public int get(int n) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0) {
				return 0;
			}
			return mobiusFunctionValues[n];
		}
	}

	/**
	 * メビウス関数を定義通り計算するクラスです。
	 * 計算量はO(logN)です。
	 */
	class PrimeFactorizationMobiusFunction implements MobiusFunction {
		@Override
		public int get(int n) {
			if (n <= 0) {
				return 0;
			}
			if (n == 1) {
				return 1;
			}
			int num = 0;
			for (int i = 2; i < n; i++) {
				if (n % i == 0) {
					n /= i;
					num++;
					if (n % i == 0) {
						return 0;
					}
				}
			}
			return num % 2 == 0 ? -1 : 1;
		}
	}

	/**
	 * 組み合わせ計算を階乗の値で行うクラスです(MOD対応)
	 * 階乗とその逆元は前計算してテーブルに格納します。
	 * C(N, N) % M の計算量は O(1)、 前計算でO(max(N, logM))です。
	 * sizeを1e8より大きい値で実行するとMLEの危険性があります。
	 * また素数以外のMODには対応していません(逆元の計算に素数の剰余環の性質を利用しているため)。
	 */
	class FactorialTableCombCalculator implements CombCalculator {
		int size;
		long[] factorialTable;
		long[] inverseFactorialTable;
		long mod;

		public FactorialTableCombCalculator(int size, long mod) {
			this.size = size;
			factorialTable = new long[size + 1];
			inverseFactorialTable = new long[size + 1];
			this.mod = mod;

			factorialTable[0] = 1L;
			for (int i = 1; i <= size; i++) {
				factorialTable[i] = (factorialTable[i - 1] * i) % mod;
			}
			inverseFactorialTable[size] = inverse(factorialTable[size], mod);
			for (int i = size - 1; i >= 0; i--) {
				inverseFactorialTable[i] = (inverseFactorialTable[i + 1] * (i + 1)) % mod;
			}
		}

		private long inverse(long n, long mod) {
			return pow(n, mod - 2, mod);
		}

		private long pow(long n, long p, long mod) {
			if (p == 0) {
				return 1L;
			}
			long half = pow(n, p / 2, mod);
			long ret = (half * half) % mod;
			if (p % 2 == 1) {
				ret = (ret * n) % mod;
			}
			return ret;
		}

		@Override
		public long comb(int n, int m) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0 || m < 0 || n < m) {
				return 0L;
			}
			return (((factorialTable[n] * inverseFactorialTable[m]) % mod) * inverseFactorialTable[n - m]) % mod;
		}
	}

	/**
	 * 組み合わせ計算をテーブルで実装したクラスです(MOD対応)
	 * 前計算でO(N^2), combはO(1)で実行できます
	 * sizeを2 * 1e4より大きい値で実行するとMLEの危険性があります
	 */
	class TableCombCalculator implements CombCalculator {
		long[][] table;
		int size;

		public TableCombCalculator(int size, long mod) {
			this.size = size;
			table = new long[size + 1][];

			table[0] = new long[1];
			table[0][0] = 1L;
			for (int n = 1; n <= size; n++) {
				table[n] = new long[n + 1];
				table[n][0] = 1L;
				for (int m = 1; m < n; m++) {
					table[n][m] = (table[n - 1][m - 1] + table[n - 1][m]) % mod;
				}
				table[n][n] = 1L;
			}
		}

		@Override
		public long comb(int n, int m) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0 || m < 0 || n < m) {
				return 0L;
			}
			return table[n][m];
		}
	}

	interface Graph {
		void link(int from, int to, long cost);
		Optional<Long> getCost(int from, int to);
		int getVertexNum();
	}

	interface FlowResolver {
		long maxFlow(int from, int to);
	}

	/**
	 * グラフの行列による実装
	 * 接点数の大きいグラフで使うとMLEで死にそう
	 */
	class ArrayGraph implements Graph {
		private Long[][] costArray;
		private int vertexNum;

		public ArrayGraph(int n) {
			costArray = new Long[n][];
			for (int i = 0; i < n; i++) {
				costArray[i] = new Long[n];
			}
			vertexNum = n;
		}

		@Override
		public void link(int from, int to, long cost) {
			costArray[from][to] = new Long(cost);
		}

		@Override
		public Optional<Long> getCost(int from, int to) {
			return Optional.ofNullable(costArray[from][to]);
		}

		@Override
		public int getVertexNum() {
			return vertexNum;
		}
	}

	/**
	 * DFS(深さ優先探索)による実装
	 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー)
	 */
	class DfsFlowResolver implements FlowResolver {
		private Graph graph;
		public DfsFlowResolver(Graph graph) {
			this.graph = graph;
		}

		/**
		 * 最大フロー(最小カット)を求める
		 * @param from 始点(source)のID
		 * @param to 終点(target)のID
		 * @return 最大フロー(最小カット)
		 */
		public long maxFlow(int from, int to) {
			long sum = 0L;
			long currentFlow;
			do {
				currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]);
				sum += currentFlow;
			} while (currentFlow > 0);
			return sum;
		}

		/**
		 * フローの実行 グラフの更新も行う
		 * @param from 現在いる節点のID
		 * @param to 終点(target)のID
		 * @param current_flow ここまでの流量
		 * @param passed 既に通った節点か否かを格納した配列
		 * @return 終点(target)に流した流量/戻りのグラフの流量
		 */
		private long flow(int from, int to, long current_flow, boolean[] passed) {
			passed[from] = true;
			if (from == to) {
				return current_flow;
			}
			for (int id = 0; id < graph.getVertexNum(); id++) {
				if (passed[id]) {
					continue;
				}
				Optional<Long> cost = graph.getCost(from, id);
				if (cost.orElse(0L) > 0) {
					long nextFlow = current_flow < cost.get() ? current_flow : cost.get();
					long returnFlow = flow(id, to, nextFlow, passed);
					if (returnFlow > 0) {
						graph.link(from, id, cost.get() - returnFlow);
						graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow);
						return returnFlow;
					}
				}
			}
			return 0L;
		}
	}

	/**
	 * 1-indexedのBIT配列
	 */
	class BinaryIndexedTree {
		private long[] array;

		public BinaryIndexedTree(int size) {
			this.array = new long[size + 1];
		}

		/**
		 * 指定した要素に値を加算する
		 * 計算量はO(logN)
		 * @param index 加算する要素の添字
		 * @param value 加算する量
		 */
		public void add(int index, long value) {
			for (int i = index; i < array.length; i += (i & -i)) {
				array[i] += value;
			}
		}

		/**
		 * 1〜指定した要素までの和を取得する
		 * 計算量はO(logN)
		 * @param index 和の終端となる要素の添字
		 * @return 1〜indexまでの和
		 */
		public long getSum(int index) {
			long sum = 0L;
			for (int i = index; i > 0; i -= (i & -i)) {
				sum += array[i];
			}
			return sum;
		}
	}

	/**
	 * 1-indexedの2次元BIT配列
	 */
	class BinaryIndexedTree2D {
		private long[][] array;

		public BinaryIndexedTree2D(int size1, int size2) {
			this.array = new long[size1 + 1][];
			for (int i = 1; i <= size1; i++) {
				this.array[i] = new long[size2 + 1];
			}
		}

		/**
		 * 指定した要素に値を加算する
		 * 計算量はO(logN * logN)
		 * @param index1 加算する要素の1次元目の添字
		 * @param index2 加算する要素の2次元目の添字
		 * @param value 加算する量
		 */
		public void add(int index1, int index2, long value) {
			for (int i1 = index1; i1 < array.length; i1 += (i1 & -i1)) {
				for (int i2 = index2; i2 < array.length; i2 += (i2 & -i2)) {
					array[i1][i2] += value;
				}
			}
		}

		/**
		 * (1,1)〜指定した要素までの矩形和を取得する
		 * 計算量はO(logN * logN)
		 * @param index1 和の終端となる要素の1次元目の添字
		 * @param index2 和の終端となる要素の2次元目の添字
		 * @return (1,1)〜(index1,index2)までの矩形和
		 */
		public long getSum(int index1, int index2) {
			long sum = 0L;
			for (int i1 = index1; i1 > 0; i1 -= (i1 & -i1)) {
				for (int i2 = index2; i2 > 0; i2 -= (i2 & -i2)) {
					sum += array[i1][i2];
				}
			}
			return sum;
		}
	}

	interface UnionFind {
		void union(int A, int B);
		boolean judge(int A, int B);
		Set<Integer> getSet(int id);
	}

	/**
	 * ArrayUnionFindの拡張
	 * MapSetで根の添字から根にぶら下がる頂点の集合が取得できるようにした
	 * getSetメソッドをO(logN * logN)に落とせているはず
	 * ただしunionメソッドは2倍の計算量になっているので注意(オーダーは変わらないはず)
	 */
	class SetUnionFind extends ArrayUnionFind {
		Map<Integer, Set<Integer>> map;
		public SetUnionFind(int size) {
			super(size);
			map = new HashMap<>();
			for (int i = 0; i < size; i++) {
				map.put(i, new HashSet<>());
				map.get(i).add(i);
			}
		}

		@Override
		protected void unionTo(int source, int dest) {
			super.unionTo(source, dest);
			map.get(dest).addAll(map.get(source));
		}

		@Override
		public Set<Integer> getSet(int id) {
			return map.get(root(id));
		}
	}

	/**
	 * 配列によるUnionFindの実装
	 * getSetメソッドはO(NlogN)なのでTLEに注意
	 */
	class ArrayUnionFind implements UnionFind {
		int[] parent;
		int[] rank;
		int size;
		public ArrayUnionFind(int size) {
			parent = new int[size];
			for (int i = 0; i < size; i++) {
				parent[i] = i;
			}
			rank = new int[size];
			this.size = size;
		}

		@Override
		public void union(int A, int B) {
			int rootA = root(A);
			int rootB = root(B);
			if (rootA != rootB) {
				if (rank[rootA] < rank[rootB]) {
					unionTo(rootA, rootB);
				} else {
					unionTo(rootB, rootA);
					if (rank[rootA] == rank[rootB]) {
						rank[rootA]++;
					}
				}
			}
		}

		protected void unionTo(int source, int dest) {
			parent[source] = dest;
		}

		@Override
		public boolean judge(int A, int B) {
			return root(A) == root(B);
		}

		@Override
		public Set<Integer> getSet(int id) {
			Set<Integer> set = new HashSet<>();
			IntStream.range(0, size).filter(i -> judge(i, id)).forEach(set::add);
			return set;
		}

		protected int root(int id) {
			if (parent[id] == id) {
				return id;
			}
			parent[id] = root(parent[id]);
			return parent[id];
		}
	}

	/**
	 * 素数のユーティリティ
	 */
	class PrimeNumberUtils {
		boolean[] isPrimeArray;
		List<Integer> primes;

		/**
		 * 素数判定の上限となる値を指定してユーティリティを初期化
		 * @param limit 素数判定の上限(この値以上が素数であるか判定しない)
		 */
		public PrimeNumberUtils(int limit) {
			if (limit > 10000000) {
				System.err.println("上限の値が高すぎるため素数ユーティリティの初期化でTLEする可能性が大変高いです");
			}
			primes = new ArrayList<>();
			isPrimeArray = new boolean[limit];
			if (limit > 2) {
				primes.add(2);
				isPrimeArray[2] = true;
			}

			for (int i = 3; i < limit; i += 2) {
				if (isPrime(i, primes)) {
					primes.add(i);
					isPrimeArray[i] = true;
				}
			}
		}

		public List<Integer> getPrimeNumberList() {
			return primes;
		}

		public boolean isPrime(int n) {
			return isPrimeArray[n];
		}

		private boolean isPrime(int n, List<Integer> primes) {
			for (int prime : primes) {
				if (n % prime == 0) {
					return false;
				}
				if (prime > Math.sqrt(n)) {
					break;
				}
			}
			return true;
		}
	}

	interface BitSet {
		void set(int index, boolean bit);
		boolean get(int index);
		void shiftRight(int num);
		void shiftLeft(int num);
		void or(BitSet bitset);
		void and(BitSet bitset);
	}

	/**
	 * Longの配列によるBitSetの実装
	 * get/setはO(1)
	 * shift/or/andはO(size / 64)
	 */
	class LongBit implements BitSet {
		long[] bitArray;

		public LongBit(int size) {
			bitArray = new long[((size + 63) / 64)];
		}

		@Override
		public void set(int index, boolean bit) {
			int segment = index / 64;
			int inIndex = index % 64;
			if (bit) {
				bitArray[segment] |= 1L << inIndex;
			} else {
				bitArray[segment] &= ~(1L << inIndex);
			}
		}

		@Override
		public boolean get(int index) {
			int segment = index / 64;
			int inIndex = index % 64;
			return (bitArray[segment] & (1L << inIndex)) != 0L;
		}

		@Override
		public void shiftRight(int num) {
			int shiftSeg = num / 64;
			int shiftInI = num % 64;
			for (int segment = 0; segment < bitArray.length; segment++) {
				int sourceSeg = segment + shiftSeg;
				if (sourceSeg < bitArray.length) {
					bitArray[segment] = bitArray[sourceSeg] >>> shiftInI;
					if (shiftInI > 0 && sourceSeg + 1 < bitArray.length) {
						bitArray[segment] |= bitArray[sourceSeg + 1] << (64 - shiftInI);
					}
				} else {
					bitArray[segment] = 0L;
				}
			}
		}

		@Override
		public void shiftLeft(int num) {
			int shiftSeg = num / 64;
			int shiftInI = num % 64;
			for (int segment = bitArray.length - 1; segment >= 0; segment--) {
				int sourceSeg = segment - shiftSeg;
				if (sourceSeg >= 0) {
					bitArray[segment] = bitArray[sourceSeg] << shiftInI;
					if (shiftInI > 0 && sourceSeg > 0) {
						bitArray[segment] |= bitArray[sourceSeg - 1] >>> (64 - shiftInI);
					}
				} else {
					bitArray[segment] = 0L;
				}
			}
		}

		public long getLong(int segment) {
			return bitArray[segment];
		}

		@Override
		public void or(BitSet bitset) {
			if (!(bitset instanceof LongBit)) {
				return;
			}
			for (int segment = 0; segment < bitArray.length; segment++) {
				bitArray[segment] |= ((LongBit)bitset).getLong(segment);
			}
		}

		@Override
		public void and(BitSet bitset) {
			if (!(bitset instanceof LongBit)) {
				return;
			}
			for (int segment = 0; segment < bitArray.length; segment++) {
				bitArray[segment] &= ((LongBit)bitset).getLong(segment);
			}
		}
	}

}


import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int M = sc.nextInt();
		int[] s = new int[M];
		int[] c = new int[M];
		for (int i = 0; i < M; i++) {
			s[i] = sc.nextInt();
			c[i] = sc.nextInt();
		}

		int number = 0;

		while (number <= 999) {
			boolean flag = true;
			int copy = number;
			int kata = 1;
			while (copy >= 10) {
				copy = copy / 10;
				kata++;
			}
			if (kata != N) {
				number++;
				continue;
			}

			if (N == 3) {
				for (int i = 0; i < M; i++) {
					if (s[i] == 1) {
						if (number / 100 != c[i])
							flag = false;
					} else if (s[i] == 2) {
						if (number % 100 / 10 != c[i])
							flag = false;
					} else if (s[i] == 3) {
						if (number % 10 != c[i])
							flag = false;
					}
				}
			} else if (N == 2) {
				for (int i = 0; i < M; i++) {
					if (s[i] == 1) {
						if (number / 10 != c[i])
							flag = false;
					} else if (s[i] == 2) {
						if (number % 10 != c[i])
							flag = false;
					}
				}
			} else if (N == 1) {
				for (int i = 0; i < M; i++) {
					if (number != c[i])
						flag = false;
				}

			}
			if (flag) {
				System.out.println(number);
				return;
			}
			number++;
		}
		System.out.println(-1);

	}

	//以下、自作ライブラリ

	/*
		int N = sc.nextInt();

		int[] a = new int[N];
		for (int i = 0; i < N; i++)
			a[i] = sc.nextInt();

		String s = sc.next();

		String[] a = new String[N];
		for (int i = 0; i < N; i++)
			a[i] = sc.next();

		int[][] a = new int[N][2];
		for (int i = 0; i < N; i++) {
			a[i][0] = sc.nextInt();
			a[i][1] = sc.nextInt();
		}
		Arrays.sort(a, (x, y) -> Integer.compare(x[0], y[0]));

		List<Integer> list = new ArrayList<>();

		Set<Integer> set = new HashSet<>();

		Map<Integer, Integer> map = new HashMap<>();

		nextLineのときは
		Scanner sc = new Scanner(System.in);
	 */

	//繰り返し二乗法による,べき乗計算で剰余を返す
	public static long modPow(long x, long n, final long mod) {
		long sum = 1;
		while (n > 0) {
			if ((n & 1) == 1) { //ビットが立っていたら
				sum = (sum * x) % mod; //x^2^k1 * x^2^k2 * x^2^k3 * ・・・
			}
			x = (x * x) % mod; //((x^2)^2)^2 ・・・
			n >>= 1;
		}
		return sum;
	}

	//組み合わせの数nCrを計算し剰余を返す
	public static long calcNumOfCombinationMod(long n, int r, final long mod) {
		long num = 1;
		for (int i = 0; i < r; i++) {
			num = (num * (n - i)) % mod;
			num = (num * modPow(i + 1, mod - 2, mod)) % mod;
		}
		return num;

	}

	//組み合わせの数nCrを計算
	public static int calcNumOfCombination(int n, int r) {
		int num = 1;
		for (int i = 1; i <= r; i++) {
			num = num * (n - i + 1) / i;
		}
		return num;
	}

	//階乗
	public static int fact(int n) {
		if (n == 1 || n == 0)
			return 1;
		else
			return n * fact(n - 1);
	}

	//指定した値以上の要素が最初に現れる位置
	//要素の数は+1（配列のズレ)
	public static long lowerBound(int n, long[] x, long y) {
		int left = 0;
		int right = n;
		while (left < right) {
			int mid = (left + right) / 2;
			if (x[mid] < y) {
				left = mid + 1;
			} else {
				right = mid;
			}
		}
		return left;
	}

	//指定した値より大きい要素が最初に現れる位置
	//要素の数は+1（配列のズレ)
	public static long upperBound(int n, long[] x, long y) {
		int left = 0;
		int right = n;
		while (left < right) {
			int mid = (left + right) / 2;
			if (x[mid] <= y) {
				left = mid + 1;
			} else {
				right = mid;
			}
		}
		return left;
	}

	//最大公約数
	public static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);
		long c = 0;
		c = a % b;
		if (c == 0)
			return b;
		return gcd(b, c);
	}

	//最小公倍数
	public static long lcm(long m, long n) {
		return m * n / gcd(m, n);
	}

	//素数判定
	public static boolean isPrime(int n) {
		if (n < 2)
			return false;
		if (n == 2)
			return true;
		if (n % 2 == 0)
			return false;

		for (int i = 3; i * i <= n; i += 2) {
			if (n % i == 0)
				return false;
		}
		return true;
	}
}

//以下、高速スキャナークラス
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	private int readByte() {
		if (hasNextByte())
			return buffer[ptr++];
		else
			return -1;
	}

	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
		return hasNextByte();
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}

	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) nl;
	}

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


import java.util.*;
import java.io.*;
class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i<n; i++) a[i] = -1;
        for(int i = 0; i<m; i++) {
            int k = sc.nextInt();
            int v = sc.nextInt();
            if(a[k-1]==-1) {
                a[k-1] = v;
            }else if(a[k-1]!=v) {
                p(-1);
                return;
            }
        }
        for(int i = 0; i<n; i++) {
            if(a[0]==-1 && n==1) a[i]=0;
            else if(a[0]==-1) a[i] = 1;
            else if(a[i] == -1) a[i]=0;
            if(a[0]==0 && n>1) {
                p(-1);
                return;
            }
            pp(a[i]);
        }
        p("");
    }
    public static String stringCopy(String str) {
        StringBuilder builder = new StringBuilder();
        builder.append(str.toCharArray());
        return builder.toString();
    }
    public static <T> void p(T element) {
	System.out.println(element);
    }
    public static <T> void pp(T element) {
        System.out.print(element);
    }
    public static int min(int a, int b, int c) {
	int min = Math.min(a,b);
	min = Math.min(min,c);
	return min;
    }
    public static int max(int a, int b,int c) {
	int max= Math.max(a,b);
	max = Math.max(max,c);
        return max;
    }
}
class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

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


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

public class Main {

    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        int N = fs.nextInt();
        int M = fs.nextInt();
        List<Integer> s = new ArrayList<>();
        List<Integer> c = new ArrayList<>();

        for (int i = 0; i < M; ++i) {
            s.add(fs.nextInt());
            c.add(fs.nextInt());
        }

        int ans = -1;
        for (int i = 0; i <= 999; ++i) {
            String str = Integer.toString(i);
            int len = str.length();
            boolean flag = true;
            for (int j = 0; j < M; ++j) {
                if (len - s.get(j) < 0 ||
                        !(Character.getNumericValue(str.charAt(s.get(j)-1)) == c.get(j))) {
                    flag = false;
                }
                if (N == 3 && s.get(j) == 1 && c.get(j) == 0) {
                    flag = false;
                }
                if (N == 2 && s.get(j) == 2 && c.get(j) == 0) {
                    flag = false;
                }
                if (N != len) {
                    flag = false;
                }
            }
            if (flag) {
                ans = i;
                break;
            }
        }

        System.out.println(ans);
    }
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}

    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }

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


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

public class Main {

    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        int N = fs.nextInt();
        int M = fs.nextInt();
        List<Integer> s = new ArrayList<>();
        List<Integer> c = new ArrayList<>();

        for (int i = 0; i < M; ++i) {
            s.add(fs.nextInt());
            c.add(fs.nextInt());
        }

        boolean flag = true;
        int ans = -1;
        for (int i = 0; i <= 999; ++i) {
            String str = Integer.toString(i);
            int len = str.length();
            flag = true;
            for (int j = 0; j < M; ++j) {
                if (len - s.get(j) < 0 ||
                        !(Character.getNumericValue(str.charAt(s.get(j)-1)) == c.get(j))) {
                    flag = false;
                }
                if (N == 3 && s.get(j) == 1 && c.get(j) == 0) {
                    flag = false;
                }
                if (N == 2 && s.get(j) == 2 && c.get(j) == 0) {
                    flag = false;
                }
            }
            if (flag) {
                ans = i;
                break;
            }
        }

        System.out.println(ans);
    }
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}

    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }

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


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int N = scan.nextInt();
		int M = scan.nextInt();
		int[] s = new int[M+1];
		int[] c = new int[M+1];
		boolean f = true;

		for (int i = 1; i < M+1; i++) {
			s[i] = scan.nextInt();
			c[i] = scan.nextInt();
		}

		if (N == 1) {
			for (int i = 1; i < M; i++) {
				if (c[i] != c[i+1]) {
					f = false;
				}
			}

			if (f) System.out.println(c[1]);
			else System.out.println(-1);

		} else {
			int[] ans = new int[N+1];
			boolean[] vst = new boolean[N+1];
			ans[1] = 1;

			for (int i = 1; i < M+1; i++) {
				if (!vst[s[i]]) {
					vst[s[i]] = true;
					ans[s[i]] = c[i];
				} else if (c[i] != ans[s[i]]) {
						f = false;
						break;
				}
			}

			if (!f || ans[1] == 0) {
				System.out.println(-1);
			} else {
				for (int i = 1; i < N+1; i++) {
					System.out.print(ans[i]);
				}
			}

		}

	}

}


#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int INF = (1<<30);
const ll INFLL = (1ll<<60);
const ll MOD = (ll)(1e9+7);

#define l_ength size

void mul_mod(ll& a, ll b){
	a *= b;
	a %= MOD;
}

void add_mod(ll& a, ll b){
	a = (a<MOD)?a:(a-MOD);
	b = (b<MOD)?b:(b-MOD);
	a += b;
	a = (a<MOD)?a:(a-MOD);
}

int s[11],c[11];
vector<int> v;

int main(void){
	int n,m,i,j,x;
	bool flag;
	cin >> n >> m;
	for(i=0; i<m; ++i){
		cin >> s[i] >> c[i];
		s[i] = n-s[i];
	}
	for(i=0; i<1000; ++i){
		x = i;
		flag = true;
		do{
			v.push_back(x%10);
			x /= 10;
		}while(x);
		if(v.l_ength()!=n){
			flag = false;
		}
		for(j=0; j<m; ++j){
			if(!flag){
				break;
			}
			if(v[s[j]]!=c[j]){
				flag = false;
				break;
			}
		}
		if(flag){
			cout << i << endl;
			return 0;
		}
		v.clear();
	}
	cout << "-1" << endl;
	return 0;
}


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

typedef long long ll;
typedef long double ld;

#define pb push_back
#define sort(s) sort(s.begin(),s.end())
#define reverse(s) reverse(s.begin(),s.end())
#define rep(i,n) for(ll (i)=0;(i)<(n);(i)++)

const ll mod = 1e9+7;

//最大公約数
ll gcd(ll a, ll b) {
    return b ? gcd(b, a%b) : a;
}

//最小公倍数
ll lcm(ll a, ll b) {
    return a / gcd(a, b) * b;
}

//素数判定
bool isPrime(ll x){
    ll i;
    if(x < 2)return 0;
    else if(x == 2) return 1;
    if(x%2 == 0) return 0;
    for(i = 3; i*i <= x; i += 2) if(x%i == 0) return 0;
    return 1;
}

//桁和
int digsum(ll n) {
    int res = 0;
    while(n > 0) {
        res += n%10;
        n /= 10;
    }
    return res;
}

//桁数
int dignum(ll n) {
    int res = 0;
    while(n > 0) {
        res++;
        n /= 10;
    }
    return res;
}

//文字列中の特定の文字カウント
ll stringcount(string s,char c){
    return count(s.cbegin(),s.cend(),c);
}

//階乗
ll ka(ll i){
    ll res=1;
    while(i>0){
        res=res*i;
        i--;
    }
    return res;
}

//ncr
ll ncr(ll x,ll y){
    ll a = x;
    ll b = 1;
    if(y>(x/2)){
        y=x-y;
    }
    for(ll i=1;i<y;i++){
        a*=x-i;
        b*=i+1;
    }
    return a/b;
}

int main(){
    int n,m;
    cin >> n >> m;
    int s[m];
    int c[m];
    int ans[n];
    rep(i,m){
        cin >> s[i] >> c[i];
    }
    //ans syokika
    rep(i,n){
        ans[i]=10;
    }

    if(m==0){
        if(n==1){
            cout << 0 << endl;
            return 0;
        }else if(n==2){
            cout << 10 << endl;
            return 0;
        }else{
            cout << 100 << endl;
            return 0;
        }
    }

    rep(i,m){
        if(ans[s[i]-1]==10){
            ans[s[i]-1]=c[i];
        }else if(ans[s[i]-1]!=c[i]){
            cout << "-1" << endl;
            return 0;
        }
    }

    bool u=true;

    rep(i,n){
        if(ans[i]==10 and n>1 and u and i==0){
            ans[i]=1;
            u=false;
        }else if(ans[i]==10){
            ans[i]=0;
        }
    }

    if(n==3 and ans[0]==0){
        cout << "-1" << endl;
        return 0;
    }
    if(n==2 and ans[0]==0){
        cout << "-1" << endl;
        return 0;
    }

    rep(i,n){
        cout << ans[i];
    }
    cout << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main () {
    int N, M;
    cin >> N >> M;
    vector<int> S(N, -1);
    for (int i = 0; i < M; i++) {
        int s, c;
        cin >> s >> c;
        s--;
        if (S[s] == -1) {
            S[s] = c;
        }
        else if (S[s] != c) {
            puts("-1");
            return 0;
        }
    }
    if (N != 1 && S[0] == 0) {
        puts("-1");
        return 0;
    }
    if (N == 1 && S[0] == -1)  {
        puts("0");
        return 0;
    }
    if (S[0] == -1) {
        S[0] = 1;
    }
    for (int i = 1; i < N; i++) {
        if (S[i] == -1) S[i] = 0;
    }
    for (int i = 0; i < N; i++) {
        cout << S[i];
    }
    cout << endl;
}


#include <bits/stdc++.h>

const int INF = 1e9;
const int MOD = 1e9 + 7;

using namespace std;

typedef long long ll;

#define REP(i, n) for (int i = 0; i < int(n); i++)
#define REPD(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, a, b) for (int i = a; i < int(b); i++)
#define FORD(i, a, b) for (int i = b - 1; i >= int(a); i--)
#define WRAP(y, x, h, w) (0 <= y && y < h && 0 <= x && x < w)

#define ALL(x) (x).begin(), (x).end()

int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };

int main()
{
    int n, m;
    cin >> n >> m;
    vector<pair<int, int>> vpii(m);
    REP(i, m)
    {
        cin >> vpii[i].first >> vpii[i].second;
    }
    vector<int> a(n, -1);
    REP(i, m)
    {
        if (a[vpii[i].first - 1] != -1 && a[vpii[i].first - 1] != vpii[i].second) {
            cout << -1 << endl;
            return 0;
        }
        if (vpii[i].first == 1 && vpii[i].second == 0) {
            cout << -1 << endl;
            return 0;
        }
        a[vpii[i].first - 1] = vpii[i].second;
    }
    REP(i, n)
    if (a[i] == -1)
        a[i] = 0;
    if (n>=2&&a[0] == 0)
        a[0] = 1;
    REP(i, n)
    cout << a[i];
    cout << endl;
}


#include <bits/stdc++.h>

const int INF = 1e9;
const int MOD = 1e9 + 7;

using namespace std;

typedef long long ll;

#define REP(i, n) for (int i = 0; i < int(n); i++)
#define REPD(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, a, b) for (int i = a; i < int(b); i++)
#define FORD(i, a, b) for (int i = b - 1; i >= int(a); i--)
#define WRAP(y, x, h, w) (0 <= y && y < h && 0 <= x && x < w)

#define ALL(x) (x).begin(), (x).end()

int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };

int main()
{
    int n, m;
    cin >> n >> m;
    vector<pair<int, int>> vpii(m);
    REP(i, m)
    {
        cin >> vpii[i].first >> vpii[i].second;
    }
    vector<int> a(n, -1);
    REP(i, m)
    {
        if (a[vpii[i].first - 1] != -1 && a[vpii[i].first - 1] != vpii[i].second) {
            cout << -1 << endl;
            return 0;
        }
        if (vpii[i].first == 1 && vpii[i].second == 0) {
            cout << -1 << endl;
            return 0;
        }
        a[vpii[i].first - 1] = vpii[i].second;
    }
    REP(i, n)
    if (a[i] == -1)
        a[i] = 0;
    if (a[0] == 0)
        a[0] = 1;
    REP(i, n)
    cout << a[i];
    cout << endl;
}


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

#define rep(i,z) for(int i = 0; i<(int)(z); i++)
#define rep1(i,z) for(int i = 1; i<=(int)(z); i++)

using namespace std;

typedef long long ll;
const ll MOD=1e9+7;
using pear = pair<int,int>;

int main(){
   int n, m; cin>>n >>m;
   vector<int> ans(n);
   ans[0] = 1;
   vector<bool> already(n);
   rep(i, n) already[i] = false;
   rep(i, m){
       int s, c; cin>>s >>c;
       s--;
        if(s == 0 && c == 0){
                cout<< -1 <<endl;
                return 0;
        }
       if(already[s] && ans[s] != c) {
           cout<< -1 <<endl;
           return 0;
        }else{

           already[s] = true;
           ans[s] = c;
       }
   }
   rep(i, n) cout<<ans[i];
   cout<<""<<endl;
}


#include<stdio.h>

int main(){
	int N, M;
	int s[5], c[5];
	int flag = 1;
	scanf("%d %d", &N, &M);
	for(int i = 0; i < M; ++i){
		scanf("%d %d", &s[i], &c[i]);
	}

	for(int i = 0; i < M; ++i){
			if(s[i] == 1 && c[i] == 0 && N != 1){
				printf("-1");
				goto F;
			}
		}
		for(int i = 0; i < M - 1; ++i){
			for(int j = i + i; j < M; ++j){
				if(s[i] == s[j] && c[i] != c[j]){
					flag = 0;
					break;
				}
			}
			if(flag == 0){
				break;
			}
		}
		if(flag == 0){
			printf("-1");
			goto F;
		}

		for(int i = 0; i < M; ++i){
				for(int j = i + 1; j < M; ++j){
					if(s[i] > s[j]){
						int t = s[i];
						s[i] = s[j];
						s[j] = t;
						t = c[i];
						c[i] = c[j];
						c[j] = t;
					}
				}
			}

	if(N == 3){
		if(M == 0)printf("100");
		else if(M == 1){
			if(s[0] == 1) printf("%d00", c[0]);
			else if(s[0] == 2) printf("1%d0", c[0]);
			else printf("10%d", c[0]);
		}
		else{
			int flag_s1_1 = 0;
			for(int i = 0; i < M; ++i){
				if(s[0] == 1){
					if(s[0] == s[M - 1]){
						printf("%d00", c[0]);
						break;
					}
					if(i == 0) printf("%d", c[i]);
					if(i > 0 && s[i] - s[i - 1] == 1) printf("%d", c[i]);
					if(i > 0 && s[i] - s[i - 1] == 2){
						printf("0");
						if(i == M - 1 && s[i] == 3) printf("%d", c[i]);
					}
					if(i == M - 1 && s[i] != 3) printf("0");
				}
				if(s[0] != 1){
					if(flag_s1_1 == 0){
						printf("1");
						if(s[0] == 3)printf("0");
						flag_s1_1 = 1;
					}
					if(i == 0) printf("%d", c[i]);
					if(i > 0 && s[i] - s[i - 1] == 1) printf("%d", c[i]);
					if(i == M - 1 && s[i] != 3) printf("0");
				}
			}
		}

	}
	if(N == 2){
		if(M == 0) printf("10");
		else if(M == 1){
			if(s[0] == 1) printf("%d0", c[0]);
			else if(s[0] == 2) printf("1%d", c[0]);
		}
		else{
			for(int i = 0; i < M; ++i){
				if(s[0] == 1){
					if(s[0] == s[M - 1]){
						printf("%d0", c[0]);
						break;
					}
					if(i == 0) printf("%d", c[i]);
					if(i > 0 && s[i] - s[i - 1] == 1)printf("%d", c[i]);
				}
				if(s[0] != 1){
					printf("1%d", c[M - 1]);
					break;
				}
			}
		}
	}
	if(N == 1){
		if(M == 0) printf("0");
		else if(c[0] == 0){
		    printf("0");
		}else{
			printf("%d", c[0]);
		}
	}
	F:return 0;
}


#include <stdio.h>
#include <stdlib.h>

struct tmp_t {
    int S;
    int C;
};

int N;
int M;
struct tmp_t T[10];

int cmpfunc( const void *a, const void *b )
{
    return( ((struct tmp_t *)a)->S, ((struct tmp_t *)b)->S );
}

long long powten( int n )
{
    int i;
    long long ret = 1;

    for( i=0; i<n; i++ ) ret *= 10;

    return( ret );
}

/***************************************
    main
***************************************/
int main( int argc, char *argv[] )
{
    int i;
    long long ret = 0;
    int digit[10];

    if( scanf( "%d%d", &N, &M ) != 2 ) {
        puts( "Input error." );
        exit( 0 );
    }

    for( i=0; i<M; i++ ) {
        if( scanf( "%d%d", &T[i].S, &T[i].C ) != 2 ) {
            puts( "Input error." );
            exit( 0 );
        }
    }

    qsort( T, M, sizeof(struct tmp_t), cmpfunc );

    for( i=0; i<M-1; i++ ) {
        if( T[i].S == T[i+1].S && T[i].C != T[i+1].C ) {
            puts( "-1" );
            exit( 0 );
        }
    }

    if( T[0].S == 1 && T[0].C == 0 && N != 1 ) {
        puts( "-1" );
        exit( 0 );
    }

    for( i=1; i<=N; i++ ) digit[i] = 0;
    for( i=0; i<M; i++ ) digit[T[i].S] = T[i].C;
    for( i=1; i<=N; i++ ) ret += powten(N-i) * digit[i];
    if( N > 1 && ret < powten(N-1) ) ret += powten(N-1);
//for(i=0; i<=N; i++ ) printf( "digit[%d] => %d\n", i, digit[i] );

    printf( "%lld\n", ret );
}


#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>

int powx(long long int x,long long int y){
  int j;
  int a;
  a=1;
  for(j=1;j<y+1-x;j++){
   a=a*10;
  }
  return(a);
}

int main(){

 long long int N,M;
  scanf("%lld %lld",&N,&M);

/*
  char A[];
  scanf("%s",A);
  */

  long long int s[M+1],c[M+1],che[N+1];
  long long int i;
  for(i=1;i<=M;i++){
   scanf("%lld %lld",&s[i],&c[i]);
   }

  long long int A;
  A=0;
  for(i=1;i<=N;i++){
    che[i]=-1;
   }

  for(i=1;i<=M;i++){

    if(che[s[i]]==-1){
      che[s[i]]=c[i];
      A += c[i]*powx(s[i],N);
    }
    else if( che[s[i]] != c[i]){
      printf("-1");
      return(0);
    }
    else{}

   }
  if(N == 1 && A == 0){
    printf("0");
  }

  else if( che[1]==0){
    printf("-1");
  }
  else{
    if(che[1]==-1){
    printf("%lld",A+powx(1,N) );
    }
    else{
    printf("%lld",A );
    }
  }

 return(0);
 }


#include<stdio.h>

int main(void)
{
    int n=0,m=0,min=0,max=0;
    int s[10]={},c[10]={},test[3]={};

    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++) scanf("%d %d",&s[i],&c[i]);

    if(n==1){ min=0;max=9;}
    if(n==2){ min=10;max=99;}
    if(n==3){ min=100;max=999;}
    for(int i=min;i<=max;i++){
        if(n==1) test[0]=i;
        else if(n==2){ test[0]=i/10;test[1]=i%10;}
        else if(n==3){ test[0]=i/100;test[1]=(i%100)/10;test[2]=i%10;}
        for(int j=0;j<m;j++){
            if(test[s[j]-1]!=c[j]) break;
            if(j==(m-1)){
                printf("%d",i);
                return 0;
            }
        }
    }
    printf("-1");
    return 0;
}


#include<stdio.h>

int main(void)
{
    int n=0,m=0,min=0,max=0;
    int s[10]={},c[10]={},test[3]={};

    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++) scanf("%d %d",&s[i],&c[i]);

    if(n==1){ min=0;max=9;}
    if(n==2){ min=10;max=99;}
    if(n==3){ min=100;max=999;}
    for(int i=min;i<=max;i++){
        if(n==1) test[0]=i%10;
        if(n==2){ test[0]=(i/10);test[1]=i%10;}
        if(n==3){ test[0]=i/100;test[1]=(i%100)/10;test[2]=i%10;}
        for(int j=0;j<m;j++){
            if(test[s[j]-1]!=c[j]) break;
            if(j==(m-1)){
                printf("%d",i);
                return 0;
            }
        }
    }
    printf("-1");
    return 0;
}


#include <stdio.h>

int main(void)
{
    int n=0,m=0,flag=1;
    int s[5]={},c[5]={},num[5]={10,10,10,10,10},numflag[5]={};
    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++){
        scanf("%d %d",&s[i],&c[i]);
    }
    if(n==1){
        for(int i=0;i<m;i++){
            if(s[i]==1 && numflag[0]==0){
                num[0]=c[i];
                numflag[0]=1;
            }
            if((s[i]==1 && num[0]!=c[i]) || s[i]!=1){
                flag=0;
                break;
            }
        }
    } else {
        for(int i=0;i<m;i++){
            if(s[i]==1){
                if(numflag[0]==0 && c[i]!=0){
                    num[0]=c[i];
                    numflag[0]=1;
                } else {
                    if(num[0]!=c[i]){
                        flag=0;
                        break;
                    }
                }
            } else {
                if(numflag[s[i]-1]==0){
                    num[s[i]-1]=c[i];
                    numflag[s[i]-1]=1;
                } else {
                    if(num[s[i]-1]!=c[i]){
                        flag=0;
                        break;
                    }
                }
            }
        }
    }

    if(flag==1 && numflag[0]==1){
        for(int i=0;i<n;i++){
            if(numflag[i]==1) printf("%d",num[i]);
            else printf("0");
        }
    } else {
        printf("-1");
    }
    return 0;
}


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);
    const sc = arg.slice(1, M + 1).map(n=>n.split(" "));

    let answer = new Array(N).fill("x");

    if(N === 1 && M === 0) {
        console.log(0);
        return;
    }

    for(let i in sc) {
        let digit  = parseInt(sc[i][0]);
        let number = sc[i][1];

        // console.log("answer:" + answer);
        // console.log("a:" + answer[digit - 1]);
        // console.log(answer[digit - 1] !== "x");

        // すでに他の数字で確保されているのはNG
        if(answer[digit - 1] !== number && answer[digit - 1] !== "x") {
            console.log(-1);
            return;
        }

        answer[digit - 1] = number;
    }

    // 最小を考える
    for(let i in answer) {
        if(answer[answer.length - i] === "x") {
            answer[answer.length - i] = 0;
        }
    }

    if(answer[0] === "x") {
        answer[0] = 1;
    }

    console.log(String(parseInt(answer.join(""))).length === N ? answer.join("") : -1);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
	input = input.split("\n");
	var a = input[0].split(" ").map(Number);
	var flag = true;
	input.shift();
	var arr = new Array(a[0]).fill("#");
	for(var i=0;i<input.length;i++){

		var mem = input[i].split(" ").map(Number);
   //   console.log(mem,arr)
    if(mem[0]==1&&mem[1]==0&&a[0]!=1) flag = false;
		if(arr[mem[0]-1]=="#"){
			arr[mem[0]-1] = mem[1];
		}else if(arr[mem[0]-1]!=mem[1]){
			flag = false;
			break;
		}
	}
	if(arr[0]=="#"&&a[0]!=1){arr[0] = 1;
                            }else if(arr[0]=="#"){
                            arr = [0];
                            }
	for(i=0;i<arr.length;i++){
		if(arr[i]=="#") arr[i] = 0;
	}
	if(flag){
		console.log(arr.join(""))
	}else{
		console.log(-1)
	}
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function Main(input) {
    var N = parseInt(input[0].split(/\s/)[0], 10);
    var M = parseInt(input[0].split(/\s/)[1], 10);
    var s = input.slice(1).map(sc => sc.split(/\s/)[0]);
    var c = input.slice(1).map(sc => sc.split(/\s/)[1]);

    var list = new Array(N);
    list.fill(-1);

    for (var i = 0; i < M; i++) {
        if (list[s[i] - 1] !== -1 && list[s[i] - 1] !== c[i]) {
            return console.log(-1);
        } else {
            list[s[i] - 1] = c[i];
        }
    }

    var result = '';

    for (var j = 0; j < N; j++) {
        if (j === 0 && N !== 1) {
            if (list[j] === -1) {
                result += '1';
            } else if (list[j] === '0') {
                return console.log(-1);
            } else {
                result += `${list[j]}`;
            }
        } else if (list[j] === -1) {
            result += '0';
        } else {
            result += `${list[j]}`;
        }
    }

    console.log(result);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n/));


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var one = nextIntArray();
  var N = one[0];
  var M = one[1];
  var list = new Array(M);
  for(var i = 0; i < M; i++){
    var tmp = nextIntArray();
    list[i] = {
      si : tmp[0],
      ci : tmp[1]
    };
  }
  for(var i = 0; i < Math.pow(10, N); i++){
    var isOK = true;
    for(var j = 0; j < M; j++){
      var check = i.toString();
      if(check.length != N){
        isOK = false;
      }
      if(check[list[j].si - 1] != list[j].ci){
        isOK = false;
      }
    }
    if(isOK){
      myout(i);
      return;
    }
  }
  myout(-1);
}


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')

const [N, M] = lines[0].split(' ').map(Number)
const s = []
const c = []

for (let i = 0; i < M; i++) {
  const row = lines[i + 1].split(' ').map(Number)
  s[i] = row[0] - 1
  c[i] = row[1]
}

;(() => {
  const n = Array(N).fill(null)
  for (let i = 0; i < M; i++) {
	if (n[s[i]] && n[s[i]] !== c[i]) {
      console.log(-1)
      return
    }
    n[s[i]] = c[i]
  }

  if (n.length > 1 && n[0] === 0) {
    console.log(-1)
    return
  }

  for (let i = 0; i < N; i++) {
    if (n[i] === null)  {
      n[i] = i === 0 ? 1 : 0
    }
  }
  console.log(n.join(''))

})()


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')

const [N, M] = lines[0].split(' ').map(Number)
const s = []
const c = []

for (let i = 0; i < M; i++) {
  const row = lines[i + 1].split(' ').map(Number)
  s[i] = row[0] - 1
  c[i] = row[1]
}

;(() => {
  const n = Array(N).fill(null)
  for (let i = 0; i < M; i++) {
	if (n[s[i]] && n[s[i]] !== c[i]) {
      console.log(-1)
      return
    }
    n[s[i]] = c[i]
  }

  if (n[0] === 0) {
    console.log(-1)
    return
  }

  for (let i = 0; i < N; i++) {
    if (n[i] === null)  {
      n[i] = i === 0 ? 1 : 0
    }
  }
  console.log(n.join(''))

})()


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	var n, m int
	if sc.Scan() {
		nm := splitToInt(sc.Text())
		n = nm[0]
		m = nm[1]
	}

	rcnt := 0
	scArr := make([][]int, m)

	for rcnt < m {
		if sc.Scan() {
			scArr[rcnt] = splitToInt(sc.Text())
			rcnt++
		}
	}

	ans := []int{}
	if n == 1 {
		// 0~99
		for i := 0; i < 10; i++ {
			strI := strconv.Itoa(i)

			for _, scV := range scArr {
				if scV[0] - 1 >= len(strI) {
					goto Next1
				}

				if string(strI[scV[0]-1]) != strconv.Itoa(scV[1]) {
					goto Next1
				}
			}
			ans = append(ans, i)
		Next1:
		}
	}

	if n == 2 {
		// 10~99
		for i := 10; i < 100; i++ {
			strI := strconv.Itoa(i)

			for _, scV := range scArr {
				if scV[0] - 1 >= len(strI) {
					goto Next2
				}

				if string(strI[scV[0]-1]) != strconv.Itoa(scV[1]) {
					goto Next2
				}
			}
			ans = append(ans, i)
		Next2:
		}
	}

	if n == 3 {
		// 100~999
		for i := 100; i < 1000; i++ {
			strI := strconv.Itoa(i)

			for _, scV := range scArr {
				if scV[0] - 1 >= len(strI) {
					goto Next3
				}

				if string(strI[scV[0]-1]) != strconv.Itoa(scV[1]) {
					goto Next3
				}
			}
			ans = append(ans, i)
		Next3:
		}
	}

	if len(ans) == 0 {
		fmt.Print("-1")
		return
	}

	sort.Ints(ans)
	fmt.Print(ans[0])
}

func splitToInt(s string) (intArr []int) {
	arr := strings.Split(s, " ")

	for _, v := range arr {
		intV, _ := strconv.Atoi(v)
		intArr = append(intArr, intV)
	}
	return
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	var n, m int
	n = nextInt()
	m = nextInt()

	ma := map[int]int{}

	if m == 0 {
		if n == 1 {
			ma[0] = 0
		} else {
			ma[0] = 1
		}
	}

	for l := 0; l < m; l++ {
		var s, c int
		s = nextInt() - 1
		c = nextInt()
		_, ok := ma[s]
		if ok && ma[s] != c {
			fmt.Println(-1)
			return
		} else if n > 1 && s == 0 && c == 0 {
			fmt.Println(-1)
			return
		} else {
			ma[s] = c
		}
	}

	ans := 0
	for i := 0; i < n; i++ {
		_, ok := ma[i]
		if !ok {
			if i == 0 && n > 1 {
				ma[i] = 1
			} else {
				ma[i] = 0
			}
		}
		ans += ma[i] * int(math.Pow10(n-i-1))
	}
	fmt.Println(ans)

}


package main

import (
        "fmt"
)

func solution(n, m int, matrix [][]int) int {
        var ans int = 1000
        for i := 0; i < 1000; i++ {
                s := fmt.Sprint(i)
                if n != len(s) {
                        continue
                }
                if m == 0 {
                        ans = min(ans, i)
                        continue
                }
                if isCond(s, matrix) {
                        ans = min(ans, i)
                }
        }
        if ans == 1000 {
                return -1
        }
        return ans
}
func isCond(str string, matrix [][]int) bool {
        for i := range matrix {
                s := matrix[i][0]
                c := matrix[i][1]
                if int(str[s-1])-48 != c {
                        return false
                }
        }
        return true
}

func min(x, y int) int {
        if x < y {
                return x
        }
        return y
}

func main() {
        var n, m int
        fmt.Scan(&n, &m)
        matrix := make([][]int, m)

        for i := 0; i < m; i++ {
                var s, c int
                fmt.Scan(&s, &c)
                matrix[i] = []int{s, c}
        }
        fmt.Println(solution(n, m, matrix))
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	N, M := ReadInt(), ReadInt()
	s := make([]int, M)
	c := make([]int, M)
	for i := 0; i < M; i++ {
		s[i], c[i] = ReadInt()-1, ReadInt()
	}

	low := 0
	if N >= 2 {
		low = 1
		for j := 0; j < N-1; j++ {
			low *= 10
		}
	}
	for i := low; i < low*10; i++ {
		str := strconv.Itoa(i)
		ok := true
		for j := 0; j < M; j++ {
			if str[s[j]]-'0' != byte(c[j]) {
				ok = false
				break
			}
		}
		if ok {
			fmt.Println(str)
			return
		}
	}
	fmt.Println(-1)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	N, M := ReadInt(), ReadInt()
	m := make(map[int]int)
	for i := 0; i < M; i++ {
		s, c := ReadInt(), ReadInt()
		if prev, exists := m[s-1]; exists && prev != c {
			fmt.Println(-1)
			return
		}
		m[s-1] = c
	}

	base := 1
	for i := 0; i < N-1; i++ {
		base *= 10
	}
	ans := 0
	leftSet := false
	for i := 0; i < N; i++ {
		if c, exists := m[i]; exists {
			if c == 0 && !leftSet && i < N-1 {
				fmt.Println(-1)
				return
			}
			ans += base * c
			leftSet = true
		} else if !leftSet {
			ans += base * 1
			leftSet = true
		}
		base /= 10
	}
	fmt.Println(ans)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	N, M := ReadInt(), ReadInt()
	m := make(map[int]int)
	for i := 0; i < M; i++ {
		s, c := ReadInt(), ReadInt()
		if prev, exists := m[s-1]; exists && prev != c {
			fmt.Println(-1)
			return
		}
		m[s-1] = c
	}

	base := 1
	for i := 0; i < N-1; i++ {
		base *= 10
	}
	ans := 0
	leftSet := false
	for i := 0; i < N; i++ {
		if c, exists := m[i]; exists {
			if c == 0 && !leftSet && i < N-1 {
				fmt.Println(-1)
				return
			}
			ans += base * c
			leftSet = true
		}
		base /= 10
	}
	fmt.Println(ans)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


N, M=gets.split.map(&:to_i)
res=?**N
M.times{
    s, c=gets.split
    s=s.to_i-1
    (p -1; exit) if res[s]!=c && res[s]!=?*
    res[s]=c
}
res[0]=(N>1 ? ?1: ?0) if res[0]==?*
res.tr! ?*, ?0
puts (N>1 && res[0]==?0 ? -1 : res)


N, M=gets.split.map(&:to_i)
res=?**N
M.times{
    s, c=gets.split
    s=s.to_i-1
    (p -1; exit) if res[s]!=c && res[s]!=?*
    res[s]=c
}
res[0]=?1 if res[0]==?* && N>1
res.tr! ?*, ?0
puts (N>1 && res[0]==?0 ? -1 : res)


n, m = gets.strip.split(' ').map{|e|e.to_i}
str = '0' * n

hash = Hash.new()
m.times do
  s, c = gets.strip.split(' ')
  if hash.include?(s) and hash[s] != c
    puts '-1'
    exit
  else
    str[s.to_i - 1] = c
    hash.store(s, c)
  end
end

if str.size != 1 and str[0] == '0'
  if hash['1'] != '0'
    str[0] = '1'
  else
    puts '-1'
    exit
  end
end

puts str


n,m = gets.chomp.split(' ').map(&:to_i)
list = []
m.times do
  list << gets.chomp.split(' ').map(&:to_i)
end
i = 0
while i <= 1000
  flag = 1
  list.each do |pair|
    if n < i.to_s.chars.size || i.to_s.chars[pair[0]-1] != pair[1].to_s
      flag = 0
    break
    end
  end
  if flag == 1
    ans = i
    break
  end
  if i == 1000
    ans = -1
  end
  i += 1
end
if n != 1 && ans.to_s.chars.size < n
  puts -1
  exit
end
puts ans


n,m = gets.chomp.split(' ').map(&:to_i)
list = []
m.times do
  list << gets.chomp.split(' ').map(&:to_i)
end
i = 0
while i <= 1000
  flag = 1
  list.each do |pair|
    if n < i.to_s.chars.size || i.to_s.chars[pair[0]-1] != pair[1].to_s
      flag = 0
    break
    end
  end
  if flag == 1
    ans = i
    break
  end
  if i == 1000
    ans = -1
  end
  i += 1
end
if n != 1
  ans.to_s.chars.size < n
  puts -1
  exit
end
puts ans


n,m=gets.split.map(&:to_i)
a=m.times.map{gets.split.map(&:to_i)}
(0..10**n).each do |i|
  s=i.to_s
  flag=true
  a.each do |i,j|
    flag=false if s[i-1]!=j.to_s
  end
  if flag
    p i
    exit
  end
end
p -1


use std::io::{self, BufRead};

fn main() {
  let stdin = io::stdin();
  let mut lines = stdin.lock().lines();
  let xs: Vec<usize> = lines.next().unwrap().unwrap().split(' ').map(|x| x.parse().unwrap()).collect();
  let (n, m) = (xs[0], xs[1]);
  let mut cs = vec![None; n];
  for _ in 0..m {
    let xs: Vec<usize> = lines.next().unwrap().unwrap().split(' ').map(|x| x.parse().unwrap()).collect();
    let (s, c) = (xs[0] - 1, xs[1]);
    if s == 0 && c == 0 && n > 1 {
      println!("-1");
      return;
    }
    match cs[s] {
      None => cs[s] = Some(c),
      Some(d) => if c != d {
        println!("-1");
        return;
      },
    };
  }
  let mut ans = 0;
  for i in 0..n {
    match cs[i] {
      None    => ans = ans * 10 + (if i == 0 && n > 1 { 1 } else { 0 }),
      Some(c) => ans = ans * 10 + c,
    };
  }
  println!("{}", ans);
}


use std::collections::HashMap;
use std::io;

fn main() {
	let mut flag = true;

	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let mut iter = buf.split_whitespace();
	let n: i32 = match iter.next().unwrap().parse(){
		Ok(n) => n,
		Err(_) => panic!(""),
	};
	let m: i32 = match iter.next().unwrap().parse(){
		Ok(n) => n,
		Err(_) => panic!(""),
	};

	let mut map: HashMap<i32, i32> = HashMap::new();
	for num in 0..m {
		let mut buf = String::new();
		io::stdin().read_line(&mut buf).expect("");
		let mut iter = buf.split_whitespace();
		let s = match iter.next().unwrap().parse(){
			Ok(n) => n,
			Err(_) => panic!(""),
		};
		let c = match iter.next().unwrap().parse(){
			Ok(n) => n,
			Err(_) => panic!(""),
		};

		match map.insert(s, c) {
			Some(n) => if n != c{
				flag = false;
			},
			None => (),
		}

	}

	if flag {
		let mut v: Vec<i32> = Vec::new();
		if n == 1 {
			match map.get(&1) {
				Some(n) => println!("{}", n ),
				None => println!("0"),
			}
		}else if n != 1 {
			match map.get(&1) {
				Some(&0) => {
					println!("-1");
				},

				Some(_) => {
					for number in 0..n {
						match map.get(&(number+1)){
							Some(n) => v.push(*n),
							None => v.push(0),
						}
					}

					for n in v {
						print!("{}", n);
					}
					print!("\n");
				},

				None => {
					v.push(1);
					for number in 1..n {
						match map.get(&(number+1)){
							Some(n) => v.push(*n),
							None => v.push(0),
						}
					}
					for n in v {
						print!("{}", n);
					}
					print!("\n");
				}
			}
		}else{
			println!("-1");
		}

	}else{
		println!("-1");
	}

}


use std::io::stdin;
use std::collections::HashMap;

fn digits(mut n: i64) -> Vec<i64> {
    let mut ans = Vec::<i64>::new();
    while n > 0 {
        ans.push(n % 10);
        n /= 10;
    }
    ans.reverse();
    return ans;
}

fn main() {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();

    let words: Vec<i64> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];
    let m = words[1];

    let mut value = HashMap::new();
    let mut impossible = false;

    for _ in 0..m {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();

        let words: Vec<i64> = line
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();

        let s = words[0];
        let c = words[1];

        if value.contains_key(&s) && value.get(&s).unwrap() != &c {
            impossible = true;
        } else {
            value.insert(s, c);
        }
    }
    if value.contains_key(&1) && value.get(&1).unwrap() == &0 && n < 1 {
        impossible = true;
    }

    if impossible {
        println!("-1");
        return;
    }

    if n == 1 && m == 0 {
        println!("0");
        return;
    }

    if n == 1 && m == 1 && value.contains_key(&1) && value.get(&1).unwrap() == &0 {
        println!("0");
        return;
    }

    let base: i64 = 10;
    for num in base.pow((n-1) as u32)..base.pow(n as u32) {
        let mut digit = vec![0];
        digit.append(&mut digits(num));
        let mut valid = true;
        for i in 1..(n+1) {
            if value.contains_key(&i) && value.get(&i).unwrap() != &digit[i as usize] {
                valid = false;
            }
        }
        if valid {
            println!("{}", num);
            return;
        }
    }
    println!("-1");
}


use whiteread::parse_line;

fn main() {
    let (n, m): (usize, usize) = parse_line().unwrap();
    let mut num: Vec<Option<u8>> = vec![None; n];

    for _ in 0..m {
        let (si, ci): (usize, u8) = parse_line().unwrap();
        if si == 1 && ci == 0 {
            println!("-1");
            return;
        }
        if let Some(c) = num[si - 1] {
            if ci != c {
                println!("-1");
                return;
            }
        } else {
            num[si - 1] = Some(ci);
        }
    }

    let mut num = num
        .iter()
        .map(|x| match x {
            Some(c) => *c,
            None => 0,
        })
        .collect::<Vec<_>>();
    if n != 1 && num[0] == 0 {
        num[0] = 1;
    }

    println!("{}", num.iter().fold(0_u32, |x, &y| x * 10 + y as u32));
}


use whiteread::parse_line;

fn main() {
    let (n, m): (usize, usize) = parse_line().unwrap();
    let mut num: Vec<Option<u8>> = vec![None; n];

    for _ in 0..m {
        let (si, ci): (usize, u8) = parse_line().unwrap();
        if si == 1 && ci == 0 {
            println!("-1");
            return;
        }
        if let Some(c) = num[si - 1] {
            if ci != c {
                println!("-1");
                return;
            }
        } else {
            num[si - 1] = Some(ci);
        }
    }

    let mut num = num
        .iter()
        .map(|x| match x {
            Some(c) => *c,
            None => 0,
        })
        .collect::<Vec<_>>();
    if num[0] == 0 {
        num[0] = 1;
    }

    println!("{}", num.iter().fold(0_u32, |x, &y| x * 10 + y as u32));
}


use proconio::input;

fn main() {
    input! {
        n: usize,
        m: usize,
        mut instructions: [(usize, usize); m],
    }

    let instructions: Vec<(usize, usize)> = instructions.iter().map(|inst| (inst.0-1, inst.1)).collect();
    let mut integer: Vec<Option<usize>> = vec![None; n];

    for instruction in &instructions {
        if n != 1 && instruction.0 == 0 && instruction.1 == 0 {
            println!("{}", -1);
            return;
        }
        if let Some(num) = integer[instruction.0] {
            if num != instruction.1 {
                println!("{}", -1);
                return;
            }
        } else {
            integer[instruction.0] = Some(instruction.1)
        }
    }

    for (i, n) in integer.iter().enumerate() {
        match n {
            Some(num) => print!("{}", num),
            None => {
                if i == 0 {
                    print!("{}", 1);
                } else {
                    print!("{}", 0);
                }
            }
        }
    }

    println!();
}


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var aryAns = [Int](repeating: -1, count: n)
    var aryS = [Int]()
    var aryC = [Int]()

    for _ in 0..<m {
        let sc = readInts()
        aryS.append(sc[0])
        aryC.append(sc[1])
    }

    var ans = String()
    if m == 0 {
        if n == 1 {
            print(0)
            return
        }
        else {
            for i in 0..<n {
                ans += i == 0 ? "1": "0"
            }
            print(ans)
            return
        }
    }

    for i in 0..<m {
        if aryAns[aryS[i]-1] != -1 && aryAns[aryS[i]-1] != aryC[i]{
            print(-1)
            return
        }
        aryAns[aryS[i]-1] = aryC[i]
    }
    if aryAns[0] == 0 && aryAns.count != 1{
        print(-1)
        return
    }

    for i in 0..<n {
        if i == 0 && aryAns.count != 1 && aryAns[i] == -1{
            ans += "1"
            continue
        }
        ans += aryAns[i] == -1 ? "0": String(aryAns[i])
    }
    print(ans)
}

main()


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var aryAns = [Int](repeating: -1, count: n)
    var aryS = [Int]()
    var aryC = [Int]()

    for _ in 0..<m {
        let sc = readInts()
        aryS.append(sc[0])
        aryC.append(sc[1])
    }

    var ans = String()
    if m == 0 {
        if n == 1 {
            print(0)
            return
        }
        else {
            for i in 0..<n {
                ans += i == 0 ? "1": "0"
            }
            print(ans)
            return
        }
    }

    for i in 0..<m {
        if aryAns[aryS[i]-1] != -1 && aryAns[aryS[i]-1] != aryC[i]{
            print(-1)
            return
        }
        aryAns[aryS[i]-1] = aryC[i]
    }
    if aryAns[0] == 0 && aryAns.count != 1{
        print(-1)
        return
    }

    for i in 0..<n {
        if i == 0 && aryAns.count != 1{
            ans += "1"
            continue
        }
        ans += aryAns[i] == -1 ? "0": String(aryAns[i])
    }
    print(ans)
}

main()


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var aryAns = [Int](repeating: -1, count: n)
    var aryS = [Int]()
    var aryC = [Int]()

    for _ in 0..<m {
        let sc = readInts()
        aryS.append(sc[0])
        aryC.append(sc[1])
    }

    var ans = String()
    if m == 0 {
        if n == 1 {
            print(0)
            return
        }
        else {
            for i in 0..<n {
                ans += i == 0 ? "1": "0"
            }
            print(ans)
            return
        }
    }

    for i in 0..<m {
        if aryAns[aryS[i]-1] != -1 && aryAns[aryS[i]-1] != aryC[i]{
            print(-1)
            return
        }
        aryAns[aryS[i]-1] = aryC[i]
    }
    if aryAns[0] == 0 && aryAns.count != 1{
        print(-1)
        return
    }

    for i in 0..<m {
        ans += aryAns[i] == -1 ? "0": String(aryAns[i])
    }
    print(ans)
}

main()


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var aryAns = [Int](repeating: -1, count: n)
    var aryS = [Int]()
    var aryC = [Int]()

    for _ in 0..<m {
        let sc = readInts()
        aryS.append(sc[0])
        aryC.append(sc[1])
    }

    var ans = String()
    if m == 0 {
        if n == 1 {
            print(0)
            return
        }
        else {
            for i in 0..<n {
                ans += i == 0 ? "1": "0"
            }
            print(ans)
            return
        }
    }

    for i in 0..<m {
        if aryAns[aryS[i]-1] != -1 && aryAns[aryS[i]-1] != aryC[i]{
            print(-1)
            return
        }
        aryAns[aryS[i]-1] = aryC[i]
    }
    if aryAns[0] == 0 {
        print(-1)
        return
    }

    for i in 0..<m {
        ans += aryAns[i] == -1 ? "0": String(aryAns[i])
    }
    print(ans)
}

main()


export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [n, m]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    if (m == 0) {
      return `${n == 1 ? 0 : n == 2 ? 10 : 100}`;
    }
    const map = {};
    for (let i = 0; i < m; i++) {
      const [s, c]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
      if ((s == 1 && c == 0 && n != 1) || (map[s] != undefined && map[s] != c)) {
        return `${-1}`;
      }
      map[s] = c;
    }
    if (n == 1) {
      return `${map[1]}`;
    }
    let result = "";
    for (let i = 1; i <= n; i++) {
      const c = map[i];
      if (c == undefined) {
        result = result + (i == 1 ? "1" : "0");
      } else {
        result = result + c;
      }
    }
    return `${result}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


const main = (input) => {
  const lines = input.trim().split("\n");
  const [N, M] = lines[0].split(' ').map(str => parseInt(str));
  const checkList = lines.slice(1).map(line => {
    const [s, c] = line.split(' ');
    return [parseInt(s - 1), c];
  });

  // 全探索
  // for (let i = 0; i < Math.pow(10, N); i++) {
  //   const strNum = i.toString();
  //   if (strNum.length == N && checkList.every(sc => strNum[sc[0]] === sc[1])) {
  //     console.log(strNum)
  //     process.exit(0);
  //   }
  // }
  // console.log(-1);

  // 順番に埋める
  let numList = Array(N).fill(-1);
  checkList.forEach(sc => {
    sc[1] = parseInt(sc[1]);
    if (numList[sc[0]] !== -1 && numList[sc[0]] !== sc[1]) {
      console.log(-1);
      process.exit(0);
    }
    numList[sc[0]] = sc[1]
  });

  if (N === 1) {
    if (numList[0] === -1) {
      console.log(0);
    } else {
      console.log(numList[0]);
    }
  } else {
    numList = numList.map((num, i) => {
      if (i === 0) {
        if (num === 0) {
          console.log(-1);
          process.exit(0);
        }
        if (num === -1) {
          return 1;
        }
      }
      if (num === -1) {
        return 0;
      }
      return num;
    })
    console.log(numList.join(""));
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N, M] = r.nn()
    const A = r.nnls()

    const lib: Record<number, number> = {}

    for (let i = 0; i < M; i++) {
      const [s, c] = A[i]

      // if (lib[s] !== undefined && lib[s] !== c) return -1
      if (s in lib && lib[s] !== c) return -1
      if (s === 1 && c === 0 && N >= 2) return -1
      lib[s] = c
    }

    if (lib[1] === undefined) {
      lib[1] = N === 1 ? 0 : 1
    }

    let res = ''

    for (let i = 1; i <= N; i++) {
      res += String(lib[i] || 0)
    }

    return res
  }

  const _io = (i = 0) => {
    const str = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map(v => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map(line => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}


import * as fs from 'fs';
// main
function main(input: string[]) {
    // param
    let n: number = 0;
    let m: number = 0;
    let sm: number[] = [];
    let cm: number[] = [];
    let ans: number = 0;
    // init
    [n, m] = input.shift().split(" ").map(x => Number(x));
    for (let mx = 0; mx < m; mx++) {
        [sm[mx], cm[mx]] = input[mx].split(" ").map(x => Number(x));
    }
    // solve
    var wn = new Array(n).fill(-1);
    for (let mx = 0; mx < m; mx++) {
        if (0 <= wn[sm[mx] - 1] && wn[sm[mx] - 1] != cm[mx]) {
            ans = -1;
            break;
        }
        wn[sm[mx] - 1] = cm[mx];
    }
    if (ans == 0) {
        for (let nx = 0; nx < n; nx++) {
            if (wn[nx] == -1) {
                wn[nx] = (nx == 0) ? 1 : 0;
            }
        }
    }
    if (wn[0] == 0) {
        ans = -1;
    }
    if (ans != -1) {
        ans = Number(wn.map(x => String(x)).join(""));
    }
    // answer
    console.log(ans);
}
// entrypoint
function entrypoint() {
    try {
        // linux
        let input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            let input = lines;
            main(input);
        });
    }
}
entrypoint();


function main(input) {
  const inputs =input.split('\n')
  const [N, M] = inputs[0].split(' ').map(Number)
  let max = N
  const sc = inputs.slice(1).map(e => {
    [s, c] = e.split(' ').map(Number)
    return [s, c]
  })
  for (let n = Math.pow(10, max - 1) - 1 ; n < 1000; n++) {
    let ok = true
    // console.log('n:', n)
    for(let i = 0; i < M; i++) {
      // console.log('sc[i]:', sc[i][0], 'str:', String(n)[sc[i][0]-1], 'c:', sc[i][1])
      if (String(n).length !== max || String(n)[sc[i][0]-1] != sc[i][1]) {
        ok = false
        break
      }
    }
    if (ok) {
      console.log(n)
      return
    }
  }
  console.log('-1')
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim())


function main(input) {
  const inputs =input.split('\n')
  const [N, M] = inputs[0].split(' ').map(Number)
  let max = N
  const sc = inputs.slice(1).map(e => {
    [s, c] = e.split(' ').map(Number)
    return [s, c]
  })
  for (let n = Math.pow(10, max - 1) - 1 ; n < 1000; n++) {
    let ok = true
    // console.log('n:', n)
    for(let i = 0; i < M; i++) {
      // console.log('sc[i]:', sc[i][0], 'str:', String(n)[sc[i][0]-1], 'c:', sc[i][1])
      if (String(n)[sc[i][0]-1] != sc[i][1]) {
        ok = false
        break
      }
    }
    if (ok) {
      console.log(n)
      return
    }
  }
  console.log('-1')
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim())


n=int(input())
vs = list(map(int, input().split()))
cs = list(map(int, input().split()))
total = 0
for i in range(n):
    if vs[i] > cs[i]:
        total += vs[i]-cs[i]
print(total)


n = int(input())
v = list(map(int, input().split()))
c = list(map(int, input().split()))
vans = 0
cans = 0
for i in range(n):
    if v[i]> c[i]:
        vans += v[i]
        cans += c[i]
print(vans - cans)


def solve():
  n = int(input())
  v = list(int(i) for i in input().split())
  c = list(int(i) for i in input().split())
  ans = 0
  for i in range(n):
    if v[i]-c[i] >= 0:
      ans += v[i]-c[i]
  print(ans)
solve()


N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))

diff = [V[i] - C[i] for i in range(N)]
diff.sort(reverse=True)

i, ans = 0,0
while diff[i] > 0:
    ans += diff[i]
    i += 1
print(ans)


N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))

diff = [0 for i in range(N)]
for i in range(N):
  diff[i] = V[i] - C[i]
diff = list(reversed(sorted(diff)))
i, ans = 0, 0
while diff[i] > 0:
  ans += diff[i]
  i += 1
print(max(ans, 0))


N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))

diff = [0 for i in range(N)]
for i in range(N):
  diff[i] = V[i] - C[i]
diff = list(reversed(sorted(diff)))
i, ans = 0, 0
while diff[i] > 0:
  ans += diff[i]
  i += 1
print(ans)


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

public class Main {
  public static void main(String[] args)throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(in.readLine());
    int[] v = new int[n];
    int[] c = new int[n];

    String[] str = in.readLine().split(" ");
    for(int i=0; i<n; i++) {
      v[i] = Integer.parseInt(str[i]);
    }
    str = in.readLine().split(" ");
    for(int i=0; i<n; i++) {
      c[i] = Integer.parseInt(str[i]);
    }

    int diff = 0;
    int ans = 0;
    for(int i=0; i<n; i++) {
      diff = v[i]-c[i];
      if(diff>0)
        ans += diff;
    }

    System.out.println(ans);
  }
}


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {

	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve() {

		int n = ni();
		int ans = 0;
		int v[] = na(n);
		for (int i = 0; i < n; i++)
			ans += Math.max(v[i] - ni(), 0);
		out.println(ans);

	}

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if (!INPUT.isEmpty())
			tr(System.currentTimeMillis() - s + "ms");
	}

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

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

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

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

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

	private char nc() {
		return (char) skip();
	}

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

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

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

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

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

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

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

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

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

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}


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

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

		int n = sc.nextInt();
		int[] v = new int[n];
		int[] c = new int[n];
		for(int i = 0; i < n; i++)
			v[i] = sc.nextInt();
		for(int i = 0; i < n; i++)
			c[i] = sc.nextInt();

		int sum = 0;
		for(int i = 0; i < n; i++) {
			if (v[i] > c[i]) sum += v[i] - c[i];
		}
		out.println(sum);

		out.close();
	}

static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() { return Double.parseDouble(next());}
}
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      int N = nextInt();
      ArrayList<Integer> plus = nextIntArray();
      ArrayList<Integer> minus = nextIntArray();
      int output = 0;
      for(int i = 0; i < N; i++){
        if(plsu.get(i) > minus.get(i)){
          output += plus.get(i) - minus.get(i);
        }
      }
      myout(output);
	}
	//Method addition frame start

	//Method addition frame end
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      int N = nextInt();
      ArrayList<Integer> plus = nextIntArray();
      ArrayList<Integer> minus = nextIntArray();
      int ouptut = 0;
      for(int i = 0; i < N; i++){
        if(plsu.get(i) > minus.get(i)){
          output += plus.get(i) - minus.get(i);
        }
      }
      myout(output);
	}
	//Method addition frame start

	//Method addition frame end
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      int N = nextInt();
      Arraylist<Integer> plus = nextIntArray();
      Arraylist<Integer> minus = nextIntArray();
      int ouptut = 0;
      for(int i = 0; i < N; i++){
        if(plsu.get(i) > minus.get(i)){
          output += plus.get(i) - minus.get(i);
        }
      }
      myout(output);
	}
	//Method addition frame start

	//Method addition frame end
}


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

int main(){
int n, sum=0,dummy;
cin >> n;
vector <int> a;
vector<int>b;
for (int i=0;i<n;i++){
cin >> dummy;
a.push_back(dummy);
}
for (int i=0;i<n;i++){
cin >> dummy;
b.push_back(dummy);
}
for (int i = 0;i<n;i++){
if (a[i]>b[i]){
sum+= a[i]-b[i];}
}
cout << sum << "\n";
return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	int v[n],c[n],sum=0;
	for(int i=0;i<n;i++){
		cin>>v[i];
	}
	for(int i=0;i<n;i++){
		cin>>c[i];
	}
	for(int i=0;i<n;i++){
		if(v[i]-c[i]>0){
			sum+=v[i]-c[i];
		}
	}
	cout<<sum;
	return 0;
}


#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main()
{
	int n, v[25], c[25], x = 0, y = 0;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> v[i];
	}
	for (int i = 0; i < n; i++) {
		cin >> c[i];
	}
	for (int i = 0; i < n; i++) {
		if (v[i] > c[i]) {
			x += v[i];
			y += c[i];
		}
	}
	cout << x - y << endl;
}


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

int main(){
  int N;cin>>N;
  int V[N],C[N],A[N];
  for(int i=0;i<N;i++) cin>>V[i];
  for(int i=0;i<N;i++) cin>>C[i];
  for(int i=0;i<N;i++) A[i]=V[i]-C[i];
  sort(A.begin(),A.end());
  reverse(A.begin(),A.end());
  int ans=0;
  for(int i=0;i<N;i++){
    if(A[i]>0) ans+=A[i];
    else break;
  }
  cout<<ans<<endl;
}


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

using ll =                   long long int;
using pll =                  pair<ll, ll>;
#define endl                 "\n"
#define space                " "
#define TLE_na_ho            ios_base::sync_with_stdio(false);cin.tie(NULL)
#define MAX_SIZE             1024
#define MOD                  1000000007
#define pb                   push_back
#define fi                   first
#define se                   second
#define rep(i,a,n)           for(ll i=a;i<n;i++)
#define repe(i,a,n)          for(ll i=a;i<=n;i++)
#define repr(i,a,n)          for(ll i=a;i>=n;i--)
#define ain(arr,n)           for(ll i1=0;i1<n;i1++ ) cin>>arr[i1]
#define aout(arr,n)          for(ll i1=0;i1<n;i1++ ) cout<<arr[i1]<<space

int main()
{
    TLE_na_ho;
    //READ THE QUESTION PROPERLY!!
    ll t;
    t=1;
    //cin>>t;
    while(t--){
    	ll n;
    	cin>>n;
    	ll v[n];
    	ain(v,n);
    	ll c[n];
    	ain(c,n);
    	sort(v,v+n,greater<int>());
    	sort(c,c+n,greater<int>());

    	ll ans=0;
    	rep(i,0,n)
    	{
    		if(v[i]>c[i])
    			ans+=v[i]-c[i];
    	}

    	cout<<ans;
    }

}


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

int main(){
  int N;cin>>N;
  int ans=0;
 // vector<int> bene;
  for(int i=0;i<N;i++){
    int V,C;cin>>V>>C;
    if(V>C) ans+=V-C;
  }
//  sort(bene.begin(),bene.end());
 /* for(int i=0;i<N;i++){
    if(bene.at(i)>0) ans+=bene.at(i);
  }*/
  cout<<ans<<endl;
}