寒假作業
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;
}
}