# 凑算式

B    DEF
A + — + ---- = 10
C    GHI

（如果显示有问题，可以参见【图1.jpg】）

6+8/3+952/714 就是一种解法，
5+3/1+972/486 是另一种解法。

DFS搜索效率较高,代码看起来也更整洁,后续补上DFS方法. 2017/3/2

#include <iostream>

using namespace std;

int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0;

bool diffrent()
{
int diff[11] = { 0 };
diff[a] = 1;
diff[b] = 1;
diff[c] = 1;
diff[d] = 1;
diff[e] = 1;
diff[f] = 1;
diff[g] = 1;
diff[h] = 1;
diff[i] = 1;
for (int i = 1; i <= 9; i++)
{
if (diff[i] != 1)
{
return false;
}
}
return true;
}

int main()
{
int count_10 = 0;
for (a = 1; a <= 9; a++)
for (b = 1; b <= 9; b++)
for (c = 1; c <= 9; c++)
for (d = 1; d <= 9; d++)
for (e = 1; e <= 9; e++)
for (f = 1; f <= 9; f++)
for (g = 1; g <= 9; g++)
for (h = 1; h <= 9; h++)
for (i = 1; i <= 9; i++)
{
if (diffrent())
{
double res = double(a) + double(b)/double(c) + double(d*100+e*10+f)/double(g*100+h*10+i);
if (res == 10.0)
{
count_10++;
}
}
}
cout<<"count: "<<count_10<<endl;
return 0;
}

DFS深度优先搜索算法

#include<stdio.h>
int ans = 0;
int num[10];
bool not_visit[10];

void Solve()
{
double sum = num[0] + (double) num[1] / num[2]
+ (double) (num[3] * 100 + num[4] * 10 + num[5])
/ (num[6] * 100 + num[7] * 10 + num[8]);
if (sum == 10)
{
ans++;
}
}

void dfs(int index)
{
if (index == 9)
{
Solve();
return;
}
for (int i = 1; i < 10; i++)
{
if (!not_visit[i])
{
not_visit[i] = true;
num[index] = i;
dfs(index + 1);
not_visit[i] = false;
}
}
}

int main()
{
dfs(0);
printf("%d\n", ans);
return 0;
}

#include <iostream>

using namespace std;

int n[9] = {0};
int count = 0;
bool idx[10] = {false};

void solve()
{
int def = n[3]*100 + n[4]*10 + n[5];
int ghi = n[6]*100 + n[7]*10 + n[8];

if (n[0]*n[2]*ghi + n[1]*ghi + n[2]*def == 10*n[2]*ghi)
{
cout<<n[0]<<" "<<n[1]<<" "<<n[2]<<" "<<n[3]<<" "<<n[4]<<" "<<n[5]<<" "<<n[6]<<" "<<n[7]<<" "<<n[8]<<endl;
count++;
}

}

void dfs(int i, int k)
{
if (i >= 10 || i <= 0)
{
return ;
}

n[k-1] = i;
idx[i] = true;

if (k == 9)
{
solve();
return ;
}

for (int x = 1; x<=9;x++)
{
if (idx[x] == false)
{
idx[x] = true;
dfs(x, k+1);
idx[x] = false;
}
}
}

int main()
{
for (int i = 1; i<=9;i++)
{
idx[i] = true;
dfs(i, 1);
idx[i] = false;
}
cout<<"count: "<< count<<endl;

return 0;
}

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int count = 0;
//sort(a, a+9); 使用next_permutation()最好使用sort()升序排列一遍
do
{
double res = a[0] + a[1] * 1.0 / a[2]
+ (a[3] * 100 + a[4] * 10 + a[5]) * 1.0
/ (a[6] * 100 + a[7] * 10 + a[8]);
if (res == 10.0)
{
count++;
}
} while (next_permutation(a, a + 9));

cout << "count: " << count << endl;
return 0;
}

http://www.cplusplus.com/reference/algorithm/next_permutation/

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120