枚举就是逐个尝试答案的一种问题求解策略
在逐个尝试时也要注意效率问题,一些没有必要的尝试就可以不去尝试以节约时间。
程序
#include <stdio.h>
int main(void)
{
int N;
scanf_s("%d", &N);
for (int a = 4; 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,Triple=(%d,%d,%d)\n", a, b, c, d);
return 0;
}
运行结果
例题2
要尽量想办法来减少尝试的次数,当然采用枚举也不用想的太多
程序
#include <stdio.h>
int main(void)
{
int p, e, i, d, k;
while (1)
{
scanf_s("%d %d %d %d", &p, &e, &i, &d);
if (p == -1)
break;
for (k = d + 1; (k - p) % 23; k++);
for (; (k - e) % 28; k += 23);
for (; (k - i) % 33; k += 23 * 28);
printf("下一个高峰期落在同一天的日子是%d\n", k - d);
}
return 0;
}
运行结果
例题3
程序
#include <stdio.h>
#include <iostream>
#include <cstdio>
#include<string.h>
using namespace std;
char Left[3][7];
char Right[3][7];
char Result[3][7];
bool IsFake(char c, bool light)
{
for (int i = 0; i < 3; i++)
{
char* left;
char* right;
if (light) {
left = Left[i];
right = Right[i];
}
else {
left = Right[i];
right = Left[i];
}
switch (Result[i][0]) {
case 'u':
if (strchr(right, c) == NULL)
return false;
break;
case 'e':
if (strchr(right, c)||strchr(left,c))
return false;
break;
case 'd':
if (strchr(left, c) == NULL)
return false;
break;
}
}
return true;
}
int main(void)
{
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))
{
printf("%c is the counterfeit coin and it is light.\n", c);
break;
}
else if (IsFake(c, false))
{
printf("%c is the counterfeit coin and it is heavy.\n", c);
break;
}
}
return 0;
}
运行结果
例题4:熄灯问题
程序
因为全部枚举将有2^30种情况,可以采用局部枚举的方法。因为该题的数据较少,char变量有8个位,可以用char类型来储存状态,用位运算来提高运行效率。
#include <stdio.h>
#include <iostream>
#include <cstdio>
#include<string.h>
using namespace std;
int GetBit(char c, int i)
{
return (c >> i) & 1;
}
void SetBit(char &c, int i,int v)
{
if (v)
c |= (1 << i);
else
c &= ~(1 << i);
}
void Flip(char& c, int i)
{
c ^= (1 << i);
}
void OutputResult(char result[])
{
printf("\n");
for (int i = 0; i<5;i++)
{
for (int j = 0; j <6; j++)
printf("%d ", GetBit(result[i], j));
printf("\n");
}
}
int main()
{
char oriLights[5];
char Lights[5];
char result[5];
char switchs;
memset(oriLights, 0, sizeof(oriLights));
//设置最初灯的状态
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j++)
{
int s;
scanf_s("%d", &s);
SetBit(oriLights[i], j, s);
}
}
for (int n = 0; n < 64; n++)//遍历首行开关的状态
{
memcpy(Lights, oriLights, sizeof(oriLights));
switchs = n;
for (int i = 0; i < 5; i++)
{
result[i] = switchs;
for(int j=0;j<6;j++)
if (GetBit(switchs, j))
{
if (j > 0)
Flip(Lights[i], j - 1);
Flip(Lights[i], j);
if (j < 5)
Flip(Lights[i], j + 1);
}
if (i < 4)
Lights[i + 1] ^= switchs;
switchs = Lights[i];
}
if (Lights[4] == 0)
{
OutputResult(result);
break;
}
}
return 0;
}
运行结果