当前位置: 代码迷 >> 综合 >> 第5届蓝桥杯大赛个人赛省赛(软件类)真题\Java语言B组\4
  详细解决方案

第5届蓝桥杯大赛个人赛省赛(软件类)真题\Java语言B组\4

热度:24   发布时间:2023-10-27 05:57:05.0

题目描述:


今有7对数字:两个1,两个2,两个3,...两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:

17126425374635

当然,如果把它倒过来,也是符合要求的。

请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。

注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。

直接上代码:
 

package wiki.zimo.exam05;public class Demo04 {public static void main(String[] args) {long start = System.currentTimeMillis();String str = "74";all:for (int a1 = 1; a1 < 7; a1++) {for (int a2 = 1; a2 < 7; a2++) {for (int a3 = 1; a3 < 7; a3++) {for (int a4 = 1; a4 < 7; a4++) {for (int a5 = 1; a5 < 7; a5++) {for (int a6 = 1; a6 < 7; a6++) {for (int a7 = 1; a7 < 7; a7++) {for (int a8 = 1; a8 < 7; a8++) {for (int a9 = 1; a9 < 7; a9++) {for (int a10 = 1; a10 < 7; a10++) {String temp = str + a1 + a2 + a3 + a4 + "4" + a5 + "7" + a6 + a7 + a8 + a9 + a10;if (judge(temp)) {System.out.println(temp);break all;}}}}}}}}}}}long end = System.currentTimeMillis();System.out.println(end - start);}public static boolean judge(String str) {if (str.matches("74[1-7]{4}4[1-7]{1}7[1-7]{5}")) {if (str.matches("\\d*6[1-7]{6}6\\d*")) {if (str.matches("\\d*5[1-7]{5}5\\d*")) {if (str.matches("\\d*3[1-7]{3}3\\d*")) {if (str.matches("\\d*2[1-7]{2}2\\d*")) {if (str.matches("\\d*1[1-7]{1}1\\d*")) {return true;}}}}}}return false;}
}

上面的解法太为暴力了,下面附上一种更为优雅的解法

package wiki.zimo.exam05;import java.util.Arrays;public class Demo04_2 {public static void main(String[] args) {int a[] = new int[14];dfs(a, a.length / 2);}private static void dfs(int[] a, int n) {if (n <= 0) {System.out.println(Arrays.toString(a));return;}for (int i = 0; i + n + 1 < a.length; i++) {if (a[i] != 0 || a[i + n + 1] != 0) continue;a[i] = a[i + n + 1] = n;dfs(a, n - 1);a[i] = a[i + n + 1] = 0;}}
}