【求助】最后一个点超时,求优化建议
查看原帖
【求助】最后一个点超时,求优化建议
121479
聪明的猪楼主2020/10/4 10:57

连我压箱底的快读快写都用上了,还是T了

代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>

int kChessboard[15];

int Read(void);
void Write(int /* n */);
void Dfs(int /* board_size */, int /* row */, int* /* total_ans */);
bool IsPlaced(int /* column */, int /* row */);

int main(void) {
  int n = 0, res = 0;
  std::memset(kChessboard, 0, sizeof (kChessboard));

  n = Read();
  Dfs(n, 1, &res);
  Write(res);
  std::putchar('\n');

  return 0;
}

int Read(void)
{
  char ch = '\0';
  int n = 0;
  ch = std::getchar();

  if (ch > '0' - 1 && ch < '9' + 1) {
    n = ch - '0';
  }

  while ((ch = std::getchar()) > '0' - 1 && ch < '9' + 1) {
    n = n * 10 + ch - '0';
  }

  return n;
}

void Write(int n)
{
  if (n > 9) {
    Write(n / 10);
  }
  std::putchar(n % 10 + '0');
}

void Dfs(int board_size, int row, int* total_ans) {
  if (row == board_size + 1) {
    if (*total_ans < 3) {
      for (int i = 1; i < board_size; ++i) {
        Write(kChessboard[i]);
        std::putchar(' ');
      }
      Write(kChessboard[board_size]);
      std::putchar('\n');
    }
    ++(*total_ans);
    return;
  }

  for (int i = 1; i < board_size + 1; ++i) {
    if (!IsPlaced(i, row)) {
      kChessboard[row] = i;
      Dfs(board_size, row + 1, total_ans);
      kChessboard[row] = 0;
    }
  }
}

bool IsPlaced(int column, int row) {
  for (int i = 1; i < row + 1; ++i) {
    if (column == kChessboard[i] ||
        std::abs(kChessboard[i] - column) == std::abs(i - row)) {
      return true;
    }
  }

  return false;
}
2020/10/4 10:57
加载中...