这是洛谷试炼场上新手村的一道Boss题, 让我头疼了好久
感觉是不难的, 枚举或搜索也许都可以, 但是就是没明确思路, 想要写的时候, 不知从何下手
看了不少题解之后, 写了回溯和枚举两种方法. 也看出了自己的一些问题.
看书做了八皇后问题之后本以为掌握了回溯, 结果还只是停留在表面和片面的层次, 其他的回溯问题因为没有见过这样的模型就只有模糊概念而无精确的过程设计.
所以, 还是应该多看多练多思多总结.
下面是十重枚举的代码, 很暴力…
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n, ans = 0;
cin >> n;
for(int a=1; a<=3; ++a) {
for(int b=1; b<=3;++b){
for(int c=1;c<=3;c++){
for(int d=1;d<=3;++d){
for(int e=1;e<=3;++e){
for(int f=1;f<=3;++f){
for(int g=1;g<=3;++g){
for(int h=1;h<=3;++h){
for(int i=1;i<=3;++i){
for(int j=1;j<=3;++j){
if(a+b+c+d+e+f+g+h+i+j == n){
ans++;
}
}
}
}
}
}
}
}
}
}
}
cout << ans << endl;
for(int a=1; a<=3; ++a) {
for(int b=1; b<=3;++b){
for(int c=1;c<=3;c++){
for(int d=1;d<=3;++d){
for(int e=1;e<=3;++e){
for(int f=1;f<=3;++f){
for(int g=1;g<=3;++g){
for(int h=1;h<=3;++h){
for(int i=1;i<=3;++i){
for(int j=1;j<=3;++j){
if(a+b+c+d+e+f+g+h+i+j == n){
printf("%d %d %d %d %d %d %d %d %d %d\n", a, b, c, d, e, f, g, h, i, j);
}
}
}
}
}
}
}
}
}
}
}
}
回溯搜索的方法看上去很美妙.
不过…
其实还是常规的回溯题…
#include <iostream>
using namespace std;
int n, cnt = 0, ans[110000][11], tmp[11];
void search(int c, int mw)
{
if(c > 10) {
if(mw == n) {
cnt++;
for(int i = 1; i <= 10; ++i) {
ans[cnt][i] = tmp[i];
}
}
} else {
for(int i = 1; i <= 3; ++i) {
tmp[c] = i;
search(c+1, mw+i);
tmp[c] = 0;
}
}
}
void show()
{
cout << cnt << endl;
for(int i = 1; i <= cnt; ++i) {
for(int j = 1; j <= 10; ++j) {
cout << ans[i][j] << ' ';
}
cout << endl;
}
}
int main()
{
cin >> n;
search(1, 0); //第一个是菜,第二个是美味
show();
}