藍橋杯-幻方填空

幻方填空

幻方是把一些數字填寫在方陣中,使得行、列、兩條對角線的數字之和都相等。

歐洲最著名的幻方是德國數學家、畫家迪勒創作的版畫《憂鬱》中給出的一個4階幻方。

他把1,2,3,…16 這16個數字填寫在4 x 4的方格中。

如圖p1.jpg所示,即:
16 ? ? 13
? ? 11 ?
9 ? ? *
? 15 ? 1

表中有些數字已經顯露出來,還有些用?和*代替。

請你計算出? 和 * 所代表的數字。並把 * 所代表的數字作爲本題答案提交。
答案是一個整數,請通過瀏覽器直接提交該數字。
注意:不要提交解答過程,或其它輔助說明類的內容。

代碼一(純C語言)

#include<stdio.h>
#include<string.h>
void transform(int*date,int num)
{
	if(num>=10)
	{
		int r1 = 16+date[0]+date[1]+13;
		int r2 = date[2]+date[3]+11+date[4];
		int r3 = 9+date[5]+date[6]+date[7];
		int r4 = date[8]+15+date[9]+1;
			
		int c1 = 16+date[2]+9+date[8];
		int c2 = date[0]+date[3]+date[5]+15;
		int c3 = date[1]+11+date[6]+date[9];
		int c4 = 13+date[4]+date[7]+1;
			
		int l1 = 16+date[3]+date[6]+1;
		int l2 = 13+11+date[5]+date[8];
		if(r1==r2&&r2==r3&&r3==r4&&c1==c2&&c2==c3&&c3==c4&&c4==l1&&l1==l2)
		printf("%d",date[7]);
		return;
	}//條件判斷 
	for(int i = num;date[i];i++){
		int t = date[i];
		for(int j=i-1;j>=num;j--) date[j+1] = date[j];
		date[num] = t;
		
		transform(date,num + 1);
		
		t = date[num];
		for(int j = num;j < i;j ++) date[j] = date[j+1];
		date[i] = t;
	}//字典序全排列-升序 
}
int main()
{
	int date[10]={2,3,4,5,6,7,8,10,12,14};
	transform(date,0);
	return 0;
}

代碼二(c++函數庫中的next_permutation()函數)

#include<stdio.h>
#include<algorithm>
using namespace std;
int date[10]={2,3,4,5,6,7,8,10,12,14};
void check(int*date)
{
		int r1 = 16+date[0]+date[1]+13;
		int r2 = date[2]+date[3]+11+date[4];
		int r3 = 9+date[5]+date[6]+date[7];
		int r4 = date[8]+15+date[9]+1;
			
		int c1 = 16+date[2]+9+date[8];
		int c2 = date[0]+date[3]+date[5]+15;
		int c3 = date[1]+11+date[6]+date[9];
		int c4 = 13+date[4]+date[7]+1;
			
		int l1 = 16+date[3]+date[6]+1;
		int l2 = 13+11+date[5]+date[8];
		if(r1==r2&&r2==r3&&r3==r4&&c1==c2&&c2==c3&&c3==c4&&c4==l1&&l1==l2)
		printf("%d",date[7]);
		return;
}
int main()
{
	do{
		check(date);//條件判斷 
	}while(next_permutation(date,date+11));
	return 0;
}

這個題不要選擇去用字符型數組,因爲到條件判斷會很麻煩,會導致你感覺邏輯沒問題,卻不輸出結果。這是因爲如果用字符型數組,會導致判斷時採用ASC碼,從而導致找不到結果。

不過如果你把字符型數組的每一位都轉化成整型,應該可行(但挺麻煩的),例如下面這串代碼的轉換:

#include<stdio.h>
int main()
{
	char a = '4';
	int c = a - '0';
	printf("%d",a);//此時輸出的是4的ASC值52,說明是字符 
	printf("%d",c);//此時輸出整型4,說明是整型
	printf("%c",c);//此處輸出4代表的ASCii值爲4的字符,說明是整型 
	return 0;
}

(不過好像只有字符0~9有對應的ASCii值(個人感覺),對於像字符’12’這類的我也不知道怎麼轉)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章