一. 枚舉
1. 2810:完美立方
http://bailian.openjudge.cn/practice/2810/
Solution:四重循環。
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
for(int a = 2; a <= N; ++a) {
for(int b = 2; b <= a - 1; ++b) {
for(int c = b; c <= a - 1; ++c) {
for(int d = c; d <= a - 1; ++d) {
if(a * a * a == b * b * b + c * c * c + d * d * d) {
printf("Cube = %d, Triple = (%d,%d,%d)\n", a, b, c, d);
}
}
}
}
}
return 0;
}
2. 4148:生理週期
http://bailian.openjudge.cn/practice/4148/
Solution:所求天數(k-d)<=21252,說明天數k<=21252+d。
#include <iostream>
#define N 21252
using namespace std;
int main() {
int p, e, i, d, caseNo = 1;
while(cin >> p >> e >> i >> d && p != -1) {
for(int k = d + 1; k <= N + d; ++k) {
if((k - p) % 23 == 0 && (k - e) % 28 == 0 && (k - i) % 33 == 0) {
printf("Case %d: the next triple peak occurs in %d days.\n", caseNo++, k - d);
break;
}
}
}
return 0;
}
更快地完成for循環:
#include <iostream>
#define N 21252
using namespace std;
int main() {
int p, e, i, d, caseNo = 1;
while(cin >> p >> e >> i >> d && p != -1) {
int k;
for(k = d + 1; (k - p) % 23; ++k);
for(; (k - e) % 28; k += 23);
for(; (k - i) % 33; k += 23 * 28);
printf("Case %d: the next triple peak occurs in %d days.\n", caseNo++, k - d);
}
return 0;
}
3. 2692:假幣問題
http://bailian.openjudge.cn/practice/2692/
Solution:枚舉每一個硬幣爲假且重或輕的情況。
<cstring> strchr
:http://www.cplusplus.com/reference/cstring/strchr/
#include <iostream>
#include <cstring>
using namespace std;
char Left[3][7];
char Right[3][7];
char result[3][7];
bool isFake(char c, bool isLight);
int main() {
int n;
cin >> n;
while(n--) {
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 << " is the counterfeit coin and it is light. " << endl;
break;
}
else if(isFake(c, false)) {
cout << c << " is the counterfeit coin and it is heavy. " << endl;
break;
}
}
}
return 0;
}
bool isFake(char c, bool isLight) {
for(int i = 0; i < 3; ++i) {
char* pLeft, *pRight;
if(isLight) {
pLeft = Left[i];
pRight = Right[i];
}
else {
pLeft = Right[i];
pRight = Left[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;
}