Time Limit:1s Memory Limit:1000k
Total Submit:2135 Accepted:1490
下载样例程序(PE)
Problem
有一个未完成的等式1 2 3 4 5 6 7 8 9=N空格内(1前面没有空格)可以填入+,-,也可以不填。
编程找出输入某个整数 N 后使等式成立的所有方案的总数。保证有解。
Input
该题含有多组测试数据,每组数据为一行,仅一个整数N。
Output
输出方案总数。
Sample Input
108
Sample Output
15
C的求解和结果
#include <stdio.h>
#include <memory.h>
int main()
{
char array[9];
int N, count;
int pos, result, i, temp, oper;
while(scanf("%d", &N) > 0){
memset(array, ' ', sizeof(array));
count = 0;
if(123456789 == N) count++;
while(1){
pos = 7;
while(1){
if(array[pos] == ' '){
array[pos] = '-';
break;
}else if(array[pos] == '-'){
array[pos] = '+';
break;
}else{
array[pos] = ' ';
pos--;
if(pos < 0) break;
}
}
if(pos < 0) break;
result = 0; temp = 1; oper = 1;
for(i = 0; i < 8; i++){
if(array[i] == ' ') temp = temp * 10 + (i+2);
else{
result += (oper * temp);
oper = (array[i] == '+') ? 1 : -1;
temp = i + 2;
}
}
result += (oper * temp);
if(result == N) count++;
}
printf("%d/n", count);
}
return 0;
}
Memory: 32K
Time: 7ms