# 一个小程序

#include <stdio.h>
#include <stdlib.h>

enum {pos_input = 0, pos_middle, pos_output};
enum {in_up = 0, in_down, left_up, right_up, left_down, right_down, out_up, out_down};

char *pos_string[] = {"up +7", "down /2",
"left_up +7", "right_up *3", "left_down /2", "right_down -5",
"up *3", "down -5"};

#define MAX_STEPS 1000
#define MAX_SOLUTIONS 1

int positions[MAX_STEPS];
int directions[MAX_STEPS];
long long ns[MAX_STEPS];
int max_step;
int solutions;

void print_solution()
{
int i;
printf("down. max_step = %d.\n", max_step);
for (i=0; i<=max_step; i++) {
printf("step: %d, pos: %d, n: %llu, direction: %s\n",
i, positions[i], ns[i], pos_string[directions[i]]);
}
printf("\n");
}

void calc(int step, long long n, int pos, int direction)
{
if (step > max_step) return;
positions[step] = pos;
directions[step] = direction;
ns[step] = n;

switch (pos) {
case pos_input:
switch (direction) {
case in_up:
calc(step + 1, n + 7, pos_middle, right_up);
calc(step + 1, n + 7, pos_middle, right_down);
calc(step + 1, n + 7, pos_middle, left_down);
break;
case in_down:
calc(step + 1, n / 2, pos_middle, right_up);
calc(step + 1, n / 2, pos_middle, right_down);
calc(step + 1, n / 2, pos_middle, left_up);
break;
default:
printf("error: case pos_input - switch (direction), direction = %d.\n", direction);
exit(1);
}
break;

case pos_middle:
switch (direction) {
case left_up:
calc(step + 1, n + 7, pos_input, in_down);
break;
case left_down:
calc(step + 1, n / 2, pos_input, in_up);
break;
case right_up:
calc(step + 1, n * 3, pos_output, out_down);
break;
case right_down:
calc(step + 1, n - 5, pos_output, out_up);
break;
}
break;

case pos_output:
if (2012 == n) {
print_solution();
solutions ++;
if (MAX_SOLUTIONS == solutions) {
exit(0);
}
}
switch (direction) {
case out_up:
calc(step + 1, n * 3, pos_middle, right_down);
calc(step + 1, n * 3, pos_middle, left_up);
calc(step + 1, n * 3, pos_middle, left_down);
break;
case out_down:
calc(step + 1, n - 5, pos_middle, right_up);
calc(step + 1, n - 5, pos_middle, left_up);
calc(step + 1, n - 5, pos_middle, left_down);
break;
default:
printf("error: pos_output - switch (direction), direction = %d\n", direction);
exit(1);
}
break;

default:
printf("error: switch (pos), directionpos = %d.\n", pos);
exit(1);
}
}

int main()
{
solutions = 0;

for (max_step = 2; max_step < MAX_STEPS; max_step++) {
calc(0, 2011, pos_input, in_down);
calc(0, 2011, pos_input, in_up);
}
return 0;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120