博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
四阶幻方/反幻方c++
阅读量:3949 次
发布时间:2019-05-24

本文共 1486 字,大约阅读时间需要 4 分钟。

1、四阶幻方

把1~16的数字填入4x4的方格中,使得行、列以及两个对角线的和都相等,满足这样的特征时称为:四阶幻方。

四阶幻方可能有很多方案。如果固定左上角为1,请计算一共有多少种方案。
比如:
1 2 15 16
12 14 3 5
13 7 10 4
8 11 6 9

以及:

1 12 13 8
2 14 7 11
15 3 10 6
16 5 4 9

就可以算为两种不同的方案。

#include 
#include
using namespace std;int a[17];int b[17];void dfs(int step); int sum=0;int main(){
memset(b,1,sizeof(b)); a[1]=1; b[1]=0; dfs(2); cout<

2、反幻方

我国古籍很早就记载着2 9 47 5 36 1 8这是一个三阶幻方。每行每列以及对角线上的数字相加都相等。下面考虑一个相反的问题。可不可以用 1~9 的数字填入九宫格,使得:每行每列每个对角线上的数字和都互不相等呢?这应该能做到。比如:9 1 28 4 37 5 6你的任务是搜索所有的三阶反幻方。并统计出一共有多少种。旋转或镜像算同一种。比如:		9 1 2 		8 4 3		7 5 6 		7 8 9 		5 4 1 		6 3 2 		2 1 9		3 4 8		6 5 7
#include 
#include
#include
using namespace std;int a[9]={
1,2,3,4,5,6,7,8,9};int main(){
int ans=0; do{
int b[8]; b[0]=a[0]+a[1]+a[2]; b[1]=a[3]+a[4]+a[5]; b[2]=a[6]+a[7]+a[8]; b[3]=a[0]+a[3]+a[6]; b[4]=a[1]+a[4]+a[7]; b[5]=a[2]+a[5]+a[8]; b[6]=a[0]+a[4]+a[8]; b[7]=a[2]+a[4]+a[6]; set < int > tem; for(int i=0;i<8;i++) tem.insert(b[i]); if(tem.size()==8) ans++; }while(next_permutation(a,a+9)); cout<

next_permutation(a,a+9)全排列函数

https://www.cnblogs.com/weixq351/p/9497108.html
#include 
#include
using namespace std;int main(){
int n; while(scanf("%d",&n)&&n){
int a[1000]; for(int i=0;i

例如输入

3

1 0 2

如果有sort()

输出为

0 1 2

0 2 1
1 0 2
1 2 0
2 0 1
2 1 0

若无

则输出为

1 0 2

1 2 0
2 0 1
2 1 0

发现函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序

你可能感兴趣的文章
MFC CListBox的使用
查看>>
VS2008 CString转char字符串
查看>>
VS2008 如何设置mfc对话框最小化
查看>>
VS2008向MFC 对话框 添加托盘图标(显示和消失)
查看>>
托盘使用--最小化到托盘,双击托盘立即还原显示
查看>>
ORACLE客户端连接配置 tnsnames.ora内容
查看>>
Ubuntu 12.04添加开机启动项
查看>>
MFC对话框使用标签页控件
查看>>
redhat中vsftp开机自启动
查看>>
修改RedHat默认登录方式
查看>>
按字段值分组表中记录
查看>>
windows批处理实现telnet登陆和运行命令--还有问题
查看>>
windows批处理实现telnet登陆和运行命令--设置缺省输入法为英文
查看>>
freetds使用-远程访问SQL Server库
查看>>
linux获得系统编码
查看>>
Ubuntu安装glib
查看>>
MySQL存储过程,生成大量数据
查看>>
查询字段值出现多次的字段值
查看>>
SQL Server表存在则进行查重 SQL语句
查看>>
redhat 9 下sqlite 3的安装及编程
查看>>