標籤:style blog os strong for ar cti div
題目:
一個經理有三個女兒,三個女兒的年齡加起來等於13,三個女兒的年齡乘起來等於經理自己的年齡,有一個下屬已知道經理的年齡,但仍不能確定經理三個女兒的年齡,這時經理說只有一個女兒的頭髮是黑的,然後這個下屬就知道了經理三個女兒的年齡。請問三個女兒的年齡分別是多少?為什嗎?
解答:
假設三個女兒按照年齡從小到大的排序時x,y,z。則1<=x,y,z<=11,x+y+z=13。能滿足這兩個條件的有很多組合,例如11(1,1,11),32(1,4,8)等。明顯11(1,1,11)這些的組合是不符合實際情況的,應該事先被排除。這裡假設經理比最大年齡的女兒至少大18歲。列舉滿足條件的組合有
27(1,3,9)
32(1,4,8)
35(1,5,7)
36(1,6,6)
36(2,2,9)
48(2,3,8)
56(2,4,7)
60(2,5,6)
63(3,3,7)
72(3,4,6)
75(3,5,5)
80(4,4,5)
因為題目中下屬知道了經理的年齡,但是依然推不出三個女兒的年齡,則說明經理的年齡在這種情況下的組合應該有兩組以上,則上述組合只有36(1,6,6)和36(2,2,9)符合題意。又因為經理說只有一個女兒的頭髮是黑的,則可進一步排除而得到答案是36(2,2,9)。
void BrainTester::AgesOfDaughter() {/* * Suppose the ages of manager‘s three daughter are respectively x,y,z. * Then, 1<=x,y,z<=11 */class Triple {public:int x, y, z;};Triple ages;int manager = 0;multimap<int, Triple> result;for (int x = 1; x <= 11; ++x) {for (int y = x; y <= 11; ++y) {for (int z = y; z <= 11; ++z) {if (x + y + z == 13) {manager = x * y * z;if (manager >= z + 18) {ages.x = x;ages.y = y;ages.z = z;result.insert(make_pair(manager, ages));}}}}}set<int> key_set;multimap<int, Triple>::iterator it;for (it = result.begin(); it != result.end(); ++it) {key_set.insert(it->first);}set<int>::iterator it_set;for (it_set = key_set.begin(); it_set != key_set.end(); ++it_set) {if (result.count(*it_set) <= 1) {result.erase(result.find(*it_set));}}for (it = result.begin(); it != result.end(); ++it) {ages = it->second;if (ages.z > ages.y)cout << it->first << "(" << ages.x << "," << ages.y << "," << ages.z<< ")" << endl;}}