题目
思路:全排列。将未填的十个数填进一个一维数组里(无重复),对这十个数进行全排列,然后对每种情况进行条件判断。
我们要求的就是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