寒假作业
package lanqiao.lanqiao_2016;
/**
* Created by ministrong on 2020/3/5.
*
寒假作业
现在小学的数学题目也不是那么好玩的。
看看这个寒假作业:
□ + □ = □
□ - □ = □
□ × □ = □
□ ÷ □ = □
(如果显示不出来,可以参见【图1.jpg】)
每个方块代表1~13中的某一个数字,但不能重复。
比如:
6 + 7 = 13
9 - 8 = 1
3 * 4 = 12
10 / 2 = 5
以及:
7 + 6 = 13
9 - 8 = 1
3 * 4 = 12
10 / 2 = 5
就算两种解法。(加法,乘法交换律后算不同的方案)
你一共找到了多少种方案?
请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
答案:64
*/
import java.util.Arrays;
/***
* 还是全排列的问题,1~13全排列
* 找出符合a【0】+a【1】=a【2】;a【3】-a【4】=a【5】,a【6】*a【7】=a【8】,a【9】/a【10】=a【11】
*/
public class Q6_2016_7_hanjia {
public static int[] a=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13};
public static void main(String[] args) {
long t1=System.currentTimeMillis();
int res=0;
do{
if(a[0]+a[1]==a[2] && a[3]-a[4]==a[5] && a[6]*a[7]==a[8] && a[9]/a[10]==a[11]) res++;
}while(nextque());
System.out.println(res);
long t2=System.currentTimeMillis();
System.out.println(t2-t1);
}
public static boolean nextque(){
int x=-1;
for(int i=a.length-1;i>0;i--){
if(a[i]>a[i-1]){
x=i-1;
break;
}
}
if(x==-1) return false;
int y=-1;
for(int i=a.length-1;i>x;i--){
if(a[i]>a[x]) {
y=i;
break;
}
}
int t=a[x];
a[x]=a[y];
a[y]=t;
Arrays.sort(a,x+1,a.length);
return true;
}
}
13个数字的全排列很耗时间,差不多一分半钟 ,可以考虑使用剪枝来优化。但是蓝桥杯这就没必要了,能在考试时间内算出来就行。
剪邮票
从左至右分别是图1、图2、图3.
package lanqiao.lanqiao_2016;
/**
* Created by ministrong on 2020/3/28.
*/
/***
*
剪邮票
如【图1.jpg】, 有12张连在一起的12生肖的邮票。
现在你要从中剪下5张来,要求必须是连着的。
(仅仅连接一个角不算相连)
比如,【图2.jpg】,【图3.jpg】中,粉红色所示部分就是合格的剪取。
请你计算,一共有多少种不同的剪取方法。
请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
答案:116
*/
import java.util.Arrays;
/****
* 思路是:从1~12中选5个数,然后看他们是否相连
* 至于怎么12选5,一种思路是使用全排列
* 对于数组{0,0,0,0,0,0,0,1,1,1,1,1}对他们做全排列,1的下标就对应每次选的数
* 这样就能枚举出所有的选法
* 然后通过dfs求证是否连通即可
*/
public class Q7_2016_7_jianyoupiao {
public static int[] a=new int[]{0,0,0,0,0,0,0,1,1,1,1,1};
public static int num=0;
public static void main(String[] args) {
int res=0;
do{
if(isok()) res++;
}while(nextque());
System.out.println(res);
}
//是否联通
public static boolean isok(){
boolean[][] t=new boolean[3][4];
int startx=0;
int starty=0;
for(int i=0;i<a.length;i++){
if(a[i]==1){
t[i/4][i%4]=true;
startx=i/4;
starty=i%4;
//System.out.println(i+1);
}
}
num=0;
return isconnect(t,startx,starty);
}
public static boolean isconnect(boolean[][] t,int x,int y){
if(x>=0 && x<3 && y>=0 && y<4 && t[x][y]) {
num++;
if(num==5) return true;
t[x][y]=false;
boolean l= isconnect(t,x+1,y)||isconnect(t,x-1,y)||isconnect(t,x,y+1)||isconnect(t,x,y-1);
//t[x][y]=true;
return l;
}
else return false;
}
//求下一个全排列.
public static boolean nextque(){
int x=-1;
for(int i=a.length-1;i>0;i--){
if(a[i]>a[i-1]){
x=i-1;
break;
}
}
if(x==-1) return false;
int y=-1;
for(int i=a.length-1;i>x;i--){
if(a[i]>a[x]) {
y=i;
break;
}
}
int t=a[x];
a[x]=a[y];
a[y]=t;
Arrays.sort(a,x+1,a.length);
return true;
}
}