枚舉法求解常見問題

完美立方:

//a的三次方等于a,b,c三個數的立方之和,這一組數稱為完美立方

#includeusing namespace std;

int main()

{

int n;

cin >> n;

int count = 0;

for (int a = 2; a <= n; a++)

{

for (int b = 2; b < a; b++)

{

for (int c = b; c < a; c++)

{

for (int d = c; d < a; d++)

{

if (a*a*a == b*b*b + c*c*c + d*d*d)

{

printf("Cube=%d,Tripe=(%d,%d,%d)", a, b, c, d);

}

count++;

}

}

}

}

cout << "times:" << count;

}

求人體的生理高峰的日子:

#includeusing namespace std;

#define N 21252

int main()

{

//人體的體力智商情商高峰分別每23,28,33天出現一次,a,b,c分別是三次高峰出現的日子,求下一次高峰出現的日子

//int a, b, c;

//cin >> a >> b >> c;

//for (int i = 0; i < 21252; i++)? ? ? ? ? //最簡單的枚舉法

//{

// if ((i - a) % 23 == 0 && (i - b) % 28 == 0 && (i - c) % 33 == 0)

// {

// cout << i;

// }

//}

int p, e, i, d, caseNo = 0;

while (cin>>p>>e>>i>>d&&p!=-1)

{

++caseNo;

int k;

for (k = d + 1; (k - p) % 23; ++k);

for (; (k - e) % 28; k += 23);

for (; (k - i) % 33; k += 23 * 28);

cout << "case" << caseNo << "下一次高峰出現在" << k - d << "天后";

}

return 0;

}

分析出假幣并判斷出假幣的重量:


#includeusing namespace std;

//若干硬幣,有一枚假幣,稱量三次,找出假幣

char Left[3][7];? //天平左邊硬幣

char Right[3][7];? ? //天平右邊硬幣

char Result[3][7];

bool IsFake(char c, bool light)? //light表示假幣為輕,否則表示假幣為重

{

for (int i = 0; i < 3; i++)

{

char *pLeft, *pRight;

if (light)

{

*pLeft = Left[0][0];

pRight = Right[i];

}

else {

pLeft = Left[i];

pRight = Right[i];

}

switch (Result[i][0])

{

case 'u':

if (strchr(pRight, c) == NULL)

{

return false;

}

break;

case 'e':

if (strchr(pLeft, c) || strchr(pRight, c))

{

return false;

}

break;

case 'd':

if (strchr(pLeft, c) == NULL)

{

return false;

}

break;

}

}

return true;

}

int main()

{

int t;

cin >> t;

while (t--)

{

for (int i = 0; i < 3; i++)

{

cin >> Left[i] >> Right[i] >> Result[i];

for (char c = 'A'; c <= 'L'; c++)

{

if (IsFake(c, true))

{

cout << c << "是假幣并且比較輕" << endl;

}

else {

if (IsFake(c, false))

{

cout << c << "是假幣并且比較重" << endl;

}

}

}

}

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容