描述
编程,百马百担问题,有100匹马,驮100担货,大马驮三担,中马驮2担,两匹小马驮一担,求大、中、小各多少匹?
智障
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <stdio.h> int main(void) { int Lar = 0, Lit = 0, Nor = 0; for(Lit = 0; Lit < 100; Lit += 2) { for( Nor = 0; Nor < 100; Nor ++ ) for(Lar = 0; Lar < 100; Lar ++) if (((Lar + Lit + Nor) == 100) && ((3 * Lar + 2 * Nor + Lit / 2) == 100)) printf("大马 = %d, 中马 = %d , 小马 = %d \n", Lar, Nor, Lit); } return 0; }
|
弱智
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <stdio.h> int main(void) { int N1,N2,N3; for(N2=0;N2<=50;N2++) { for(N1=0;N1<=(100-N2*2)/3;N2++) { N3=100-N1*3-N2*2; if((N1+N2+N3)==100) printf("大马%d只,中马%d只,小马%d只\n",N1,N2,N3); } } return 0; }
|
正确的姿势
像这种规模的数据,不优化其实也能秒出的…
无聊了,也写一下:
设大马x匹,中马y匹,小马z匹,则由题设可列方程组:
3x + 2y + z/2 = 100 (1)
x + y + z = 100 (2)
x >= 0 (3)
y >= 0 (4)
z >= 0 && z % 2 == 0 (5)
(1)(2)可化为:
3x + 2y = 100 - z/2 (6)
x + y = 100 - z (7)
可得
x = 1.5z - 100 (8)
y = 200 - 2.5z (9)
将(8)(9)带入(3)(4)可得:
200/3 <= z <= 80 (10)
又由(5)可知:
68 <= z <= 80且z为偶数(11)
从而由(11)(8)(9)可以写出如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> int main() { int x, y, z; for(z = 68; z <= 80; z += 2){ x = (z>>1)*3 - 100; y = 200 - (z>>1)*5; printf("大马%d匹,中马%d匹,小马%d匹\n", x, y, z); } return 0; }
|