洛谷 P1149 火柴棒等式
题目
题目描述
给你n根火柴棍,你可以拼出多少个形如“A+B=C”的等式?等式中的A、B、C是用火柴棍拼出的整数(若该数非零,则最高位不能是0)。用火柴棍拼数字0-9的拼法如图所示:
注意:
加号与等号各自需要两根火柴棍
如果A≠B,则A+B=C与B+A=C视为不同的等式(A、B、C>=0)
n根火柴棍必须全部用上
输入输出格式
输入格式:
输入文件matches.in共一行,又一个整数n(n<=24)。
输出格式:
输出文件matches.out共一行,表示能拼成的不同等式的数目。
输入输出样例
输入样例#1:
样例输入1:
14
样例输入2:
18
输出样例#1:
样例输出1:
2
样例输出2:
9
说明
【输入输出样例1解释】
2个等式为0+1=1和1+0=1。
【输入输出样例2解释】
9个等式为:
0+4=4
0+11=11
1+10=11
2+2=4
2+7=9
4+0=4
7+2=9
10+1=11
11+0=11
题解
因为等号、加号各需2个火柴棒,那么n根火柴棒中只有n-4根用来摆数字,而n最大只有24,那么我们可以大概求出数字的最大值,因为7和1所用的火柴棒最少,而771+1=772用了19根火柴棒,1111+1=1112用了21根火柴棒,所以我们只要枚举1到771即可。
代码(Pascal)
const cost:array[0..9]of longint=(6,2,5,5,4,5,6,3,7,6);
var n,ans:longint;
procedure init;
begin
readln(n);
n:=n-4;
end;
procedure main;
var i,j,x,a,b,c:longint;
begin
ans:=0;
for i:=0 to 771 do
begin
x:=i;a:=0;
if x=0 then a:=a+cost[x];
while x<>0 do
begin
a:=a+cost[x mod 10];
x:=x div 10;
end;
if a<=n-4 then
for j:=0 to 771 do
begin
x:=j;b:=0;
if x=0 then b:=b+cost[x];
while x<>0 do
begin
b:=b+cost[x mod 10];
x:=x div 10;
end;
if a+b>n-2 then continue;
x:=i+j;c:=0;
if x=0 then c:=c+cost[x];
while x<>0 do
begin
c:=c+cost[x mod 10];
x:=x div 10;
end;
if a+b+c=n then inc(ans);
end;
end;
end;
procedure print;
begin
write(ans);
end;
begin
init;
main;
print;
end.