处理“所有组合”项目的最佳方法是什么?

时间:2010-11-11 02:58:09

标签: performance algorithm

3 个答案:

答案 0 :(得分:2)

您可以使用标准模板库(STL)中的maphash_map。这些结构有效地存储键值对。在使用它们之前先阅读它们,但它们可能会给你一个很好的起点。提示:你计算的整数可能会成为好键。

答案 1 :(得分:0)

答案 2 :(得分:0)

您可以尝试一些元编程,如下所示。它的优点是使用C本身来计算表达式,而不是你试图做自己的求值程序(并且可能出错):

#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

int main (void) {
  int n1, n2, n3;
  const char *ops[] = {" + ", " - ", " * ", " / ", " % ", 0};
  const char **op1, **op2;
  ofstream of;

  of.open ("prog2.cpp", ios::out);

  of << "#include <iostream>\n";
  of << "using namespace std;\n";
  of << "#define IXCOUNT 49\n\n";
  of << "static int mkIdx (int tot) {\n";
  of << "  int ix = (IXCOUNT / 2) + tot;\n";
  of << "  if ((ix >= 0) && (ix < IXCOUNT)) return ix;\n";
  of << "  cout << \"Need more index space, "
     << "try \" << IXCOUNT + 1 + (ix - IXCOUNT) * 2 << \"\\n\";\n";
  of << "  return -1;\n";
  of << "}\n\n";
  of << "int main (void) {\n";
  of << "  int tot, ix, used[IXCOUNT];\n\n";
  of << "  for (ix = 0; ix < sizeof(used)/sizeof(*used); ix++)\n";
  of << "    used[ix] = 0;\n\n";

  for (n1 = 2; n1 <= 4; n1++) {
    for (n2 = 2; n2 <= 4; n2++) {
      if (n2 != n1) {
        for (n3 = 2; n3 <= 4; n3++) {
          if ((n3 != n1) && (n3 != n2)) {
            for (op1 = ops; *op1 != 0; op1++) {
              for (op2 = ops; *op2 != 0; op2++) {
                of << "    tot = " << n1 << *op1 << n2 << *op2 << n3 << ";\n";
                of << "    if ((ix = mkIdx (tot)) < 0) return ix;\n";
                of << "    if (!used[ix])\n";
                of << "      cout << " << n1 << " << \"" << *op1 << "\" << "
                   << n2 << " << \"" << *op2 << "\" << " << n3
                   << " << \" = \" << tot << \"\\n\";\n";
                of << "    used[ix] = 1;\n\n";
              }
            }
          }
        }
      }
    }
  }

  of << "    return 0;\n";
  of << "}\n";

  of.close();

  system ("g++ -o prog2 prog2.cpp ; ./prog2");
  return 0;
}

这会给你:

2 + 3 + 4 = 9
2 + 3 - 4 = 1
2 + 3 * 4 = 14
2 + 3 / 4 = 2
2 + 3 % 4 = 5
2 - 3 + 4 = 3
2 - 3 - 4 = -5
2 - 3 * 4 = -10
2 - 3 % 4 = -1
2 * 3 + 4 = 10
2 * 3 * 4 = 24
2 / 3 + 4 = 4
2 / 3 - 4 = -4
2 / 3 * 4 = 0
2 % 3 + 4 = 6
2 % 3 - 4 = -2
2 % 3 * 4 = 8
2 * 4 + 3 = 11
2 / 4 - 3 = -3

我并非完全将某些作为一项任务交付的智慧: - )

相关问题