P1092 Insect-eating calculation - DFS and binary processing






import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static int N;
	static int[] num = new int[30];
	static boolean[] used = new boolean[30];
	static char[][] s = new char[5][30];

	static int x(char ch) {
		return ch - 'A' + 1;
	}

	static void dfs(int x, int y, int carry) {
		/*
		 * x:column
		 * y: row
		 * carry: carry
		 */
		if (x == 0) {
			if (carry == 0) {//The last column cannot have carry
				for (int i = 1; i < N; i++) {
					System.out.print(num[i] + " ");
				}
				System.out.println(num[N]);
			}
			return;
		}

		for (int i = x - 1; i >= 1; i--) {
			int x1 = num[x(s[1][i])]; //Number represented by the first line
			int x2 = num[x(s[2][i])]; //The number represented by the second line
			int x3 = num[x(s[3][i])]; //The number represented by the third row
			if (x1 == -1 || x2 == -1 || x3 == -1)
				continue;
			if ((x1 + x2) % N != x3 && (x1 + x2 + 1) % N != x3)
				return;
		}

		if (num[x(s[y][x])] == -1) {
			for (int i = N - 1; i >= 0; i--) {//Reverse enumeration
				if (!used[i]) {
					if (y != 3) {
						num[x(s[y][x])] = i;
						used[i] = true;
						dfs(x, y + 1, carry);
						num[x(s[y][x])] = -1;
						used[i] = false;
					} else {
						int sum = num[x(s[1][x])] + num[x(s[2][x])] + carry;// two numbers plus their carry
						if (sum % N != i)
							continue;
						used[i] = true;
						num[x(s[3][x])] = i;
						dfs(x - 1, 1, sum / N);// search the next column, the carry needs to be changed
						num[x(s[3][x])] = -1;
						used[i] = false;
					}
				}
			}
		} else {
			if (y != 3)
				dfs(x, y + 1, carry);
			else {
				int sum = num[x(s[1][x])] + num[x(s[2][x])] + carry;
				if (sum % N != num[x(s[3][x])])
					return;
				dfs(x - 1, 1, sum / N);// search the next column, the carry needs to be changed
			}
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		for (int i = 1; i <= 3; i++) {
			char[] temp = sc.next().toCharArray();
			for (int j = 0; j < temp.length; j++) {
				s[i][j + 1] = temp[j];
			}
		}
		Arrays.fill(num, -1);
		dfs(N, 1, 0);
	}
}



Memo: More ideas in the future. (Really not enough time recently aaaa, forget me.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325702084&siteId=291194637