【蓝桥杯】幻方填空(C++全排列 next_permutation)

题目
在这里插入图片描述

思路:全排列。将未填的十个数填进一个一维数组里(无重复),对这十个数进行全排列,然后对每种情况进行条件判断。
在这里插入图片描述

我们要求的就是q[7]。

这里c++STL提供了一个全排列函数:

bool next_permutation (Iterator first, Iterator last);

1.包含在algorithm头文件中。
2.函数的返回类型是布尔值。从迭代器的起始值到末尾进行全排列。如果未排完所有情况返回false,排完的话返回true。
3.要注意的是,使用该函数时,数据必须是提前排好序的。如果未排好序会缺少某些情况。
有序的情况

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    string a = "bac";
    sort(a.begin(), a.end());
    do
    {
        cout << a << endl;
    }while(next_permutation(a.begin(), a.end()));
    
    return 0;
}

输出
在这里插入图片描述
无序的情况

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    string a = "bac";
    //sort(a.begin(), a.end());
    do
    {
        cout << a << endl;
    }while(next_permutation(a.begin(), a.end()));
    
    return 0;
}

输出
在这里插入图片描述

题解代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

int a[] = {2, 3, 4, 5, 6, 7, 8, 10, 12, 14}; //矩阵中未填的数
vector<int> q;

void solve(vector<int> &q)
{
    //四行
    int r1 = 29 + q[0] + q[1];
    int r2 = 11 + q[2] + q[3] + q[4];
    int r3 = 9 + q[5] + q[6] + q[7];
    int r4 = 16 + q[8] + q[9];
    //四列
    int c1 = 25 + q[2] + q[8];
    int c2 = 15 + q[0] + q[3] + q[5];
    int c3 = 11 + q[1] + q[6] + q[9];
    int c4 = 14 + q[4] + q[7];
    //两条对角线
    int l = 17 + q[3] + q[6];
    int r = 24 + q[5] + q[8];
    
    if(r1 == r2 && r2 == r3 && r3 == r4 && r4 == c1 && c1 == c2 && c2 == c3 && c3 == c4 && c4 && c4== l && l == r)
        cout << q[7];
}
int main()
{
    for(int i = 0; i < 10; i++)
    {
        q.push_back(a[i]);
    }
    do
    {
        solve(q);
    }while(next_permutation(q.begin(), q.end()));
    
    return 0;
}
//答案:12
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值