POJ 1950

来源:互联网 发布:java打印五角星 编辑:程序博客网 时间:2024/05/21 06:41

1~n添加 + - .的符号使得表达式的值为0

其中.符号为结合符 1.2 == 12

输入表达式 和 其个数

若多于20个 输出前20个

dps每次记录当前的和  和  前一次加上去的数

#include<iostream>using namespace std;char op[15];int n;int cnt;void disp(){     int i;     for (i = 1; i < n; i++)         printf("%d %c ", i, op[i]);     printf("%d\n", n);}void dps(int deep, int num, int pre){     if (deep == n)     {              if (num == 0)              {                      cnt++;                      if (cnt <= 20) disp();              }              return;     }     op[deep] = '+';     dps(deep + 1, num + deep + 1, deep + 1);     op[deep] = '-';     dps(deep + 1, num - deep - 1, deep + 1);     op[deep] = '.';     int now, k;     if (deep + 1 >= 10) now = pre * 100 + deep + 1;     else now = pre * 10 + deep + 1;     int i = deep - 1;     while (i >= 1 && op[i] == '.') i--;     if (i == 0) k = now;     else if (op[i] == '+') k = num - pre + now;          else k = num + pre - now;     dps(deep + 1, k, now); }int main(){    while (scanf("%d", &n) != EOF)    {          cnt = 0;          dps(1,1,1);          printf("%d\n", cnt);         }//    system("pause");    return 0;}