问题如下:
若有四个砝码称出1~30g间所有整数克,则四个砝码各重多少?
结果是 (1)+(2)+(7)+(20)。
程序如下:
#include
bool can_get(const int sum, const int a, const int b,const int c,const int d, bool verbose= false);
int set_value(const int val, const int status);
int main()
{
int can_get_acct = 0;
for(int ia=1;ia<30;ia++)
for(int ib=1;ib<30;ib++)
for(int ic=1;ic<30;ic++)
for(int id=1;id<30;id++)
{
can_get_acct = 0;
for(int sum=1;sum<31;sum++)
{
if (can_get(sum,ia,ib,ic,id))
can_get_acct++;
}
if(can_get_acct==30)
{
fprintf(stderr,"eurekkkkkkkkkkkkkkkkkkkkkkka!\n");
fprintf(stderr,"ahooooo:(%d)+(%d)+(%d)+(%d)\n",ia,ib,ic,id);
for(int sum=1;sum<31;sum++)
can_get(sum,ia,ib,ic,id,true);
return 0;
}
}
return 0;
}
bool can_get(const int sum, const int a,const int b,const int c,const int d, bool verbose)
{
int sa,sb,sc,sd;
for(int ia=0;ia<3;ia++)
for(int ib=0;ib<3;ib++)
for(int ic=0;ic<3;ic++)
for(int id=0;id<3;id++)
{
sa = set_value(a, ia);
sb = set_value(b, ib);
sc = set_value(c, ic);
sd = set_value(d, id);
if (sa+sb+sc+sd==sum)
{
if (verbose)
fprintf(stderr,"ahooooo:(%d)+(%d)+(%d)+(%d)=%d\n",sa,sb,sc,sd,sum);
return true;
}
}
return false;
}
int set_value(const int val, const int status)
{
if (status == 0)
return val;
else if (status == 1)
return 0-val;
else
return 0;
}
运行结果如下:
eurekkkkkkkkkkkkkkkkkkkkkkka!
ahooooo:(1)+(2)+(7)+(20)
ahooooo:(1)+(0)+(0)+(0) =1
ahooooo:(0)+(2)+(0)+(0) =2
ahooooo:(1)+(2)+(0)+(0) =3
ahooooo:(-1)+(-2)+(7)+(0) =4
ahooooo:(0)+(-2)+(7)+(0) =5
ahooooo:(1)+(-2)+(7)+(0) =6
ahooooo:(0)+(0)+(7)+(0) =7
ahooooo:(1)+(0)+(7)+(0) =8
ahooooo:(0)+(2)+(7)+(0) =9
ahooooo:(1)+(2)+(7)+(0) =10
ahooooo:(0)+(-2)+(-7)+(20) =11
ahooooo:(1)+(-2)+(-7)+(20) =12
ahooooo:(0)+(0)+(-7)+(20) =13
ahooooo:(1)+(0)+(-7)+(20) =14
ahooooo:(0)+(2)+(-7)+(20) =15
ahooooo:(1)+(2)+(-7)+(20) =16
ahooooo:(-1)+(-2)+(0)+(20) =17
ahooooo:(0)+(-2)+(0)+(20) =18
ahooooo:(1)+(-2)+(0)+(20) =19
ahooooo:(0)+(0)+(0)+(20) =20
ahooooo:(1)+(0)+(0)+(20) =21
ahooooo:(0)+(2)+(0)+(20) =22
ahooooo:(1)+(2)+(0)+(20) =23
ahooooo:(-1)+(-2)+(7)+(20) =24
ahooooo:(0)+(-2)+(7)+(20) =25
ahooooo:(1)+(-2)+(7)+(20) =26
ahooooo:(0)+(0)+(7)+(20) =27
ahooooo:(1)+(0)+(7)+(20) =28
ahooooo:(0)+(2)+(7)+(20) =29
ahooooo:(1)+(2)+(7)+(20) =30