# 侯捷先生网站上的一个编程题目，小弟给出一个解答，请高人指教

http://www.csdn.net/expert/jjhou/course-generic-yzu.txt
2001 期末作业题目：

0 1 2 3 4
2 3 4 0 1
4 0 1 2 3
1 2 3 4 0
3 4 0 1 2

o. 资料结构可用 vectors
o. 演算法可用 next_permutation(), for_each,
o. 辅助工具可用 function objects, iterator adaptors.
o. 萤幕输入/输出可用 iostream
o. 档案输出可用 ofstream
o. 资料格式化可用 ostringstream
o. 时间计算可用 struct tm, time_t, time(), localtime()

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
typedef vector<vector<int> > Matrix;

template<typename T>
void init_vec(vector<T> &vec, int n);
bool check(const Matrix &matrix, int l, int n);
void print(ostream &os, const Matrix &matrix);
int input();

class print_vec { //functor for print a vector
public:
print_vec(ostream &rhs = cout):os_(rhs) {}
template<typename T>
void operator ()(const vector<T> &vec) {
copy(vec.begin(), vec.end(), ostream_iterator<T>(os_, " "));
os_ << "\n";
}
private:
ostream &os_;
};

int main()
{
ofstream os("result.txt");
if(!os) {
cout << "Open output file failed!" << endl;
exit(1);
}

int n = input();
Matrix matrix(n);

clock_t ct_start;
ct_start = clock();

int total = 0;
int l = 0;
bool need_init = true;
while(l >= 0) {
bool is_available;

if (need_init)
init_vec(matrix[l], n);

do {
if (is_available = check(matrix, l, n))
break;
} while(next_permutation(matrix[l].begin(), matrix[l].end()));

if(is_available) { //回溯条件
need_init = true;
++l;
} else {
need_init = false;
--l; //回溯
}

if (l == n) { //找到一组解
--l; //回溯
os << "Number." << ++total << '\n';
print(os, matrix);
need_init = false;
}

while(!(need_init || next_permutation(matrix[l].begin(), matrix[l].end()) )){
--l;
if (l == -1)
break;
}
}
cout << "\nFound " << total << " solutions. \n" ;
cout << "The elapsed time is: " << ((double)clock() - ct_start) / CLK_TCK << endl;
}

template<typename T>
void init_vec(vector<T> &vec, int n)
{ // initialize a vector
vec.clear();
for(int i = 0; i < n; ++i)
vec.push_back(i);
}

bool check(const Matrix &matrix, int l, int n)
{ //check the request
for( int i = 0; i <= l - 1; ++i)
for (int j = i + 1; j <= l; j++) {
if (!inner_product(matrix[i].begin(), matrix[i].end(), matrix[j].begin(), 1, multiplies<int>(), minus<int>()))
return false;
}
for( int i = 0; i <= l - 1; ++i)
for (int j = i + 1; j <= l; j++) {
if (matrix[i][i] == matrix[j][j] || matrix[i][n-i-1] == matrix[j][n-j-1])
return false;
}
return true;
}

void print(ostream &os, const Matrix &matrix)
{
for_each(matrix.begin(), matrix.end(), print_vec(os));
os << endl;
}

int input()
{
int n;
do {
cout << "Input the dimension (1~7) : " ;
cin >> n;
if (n == -1)
exit(0);
if (n < 1 || n > 7)
cout << "Out of range, try again or -1 to exit.\n";

} while(n < 1 || n > 7);

return n;
}

...全文
108 5 打赏 收藏 举报

5 条回复

• 打赏
• 举报

• 打赏
• 举报

jjyycc 2001-11-26
"侯捷先生网站上的一个编程题目，小弟给出一个解答，请高人指教",你不是高人吗？
• 打赏
• 举报

yinx 2001-11-24

• 打赏
• 举报

• 打赏
• 举报

C语言

6.6w+

C语言相关问题讨论

2001-11-23 11:00