【挖坟】【求助】还是80分,第三个点WA了
查看原帖
【挖坟】【求助】还是80分,第三个点WA了
121479
聪明的猪楼主2020/10/3 17:25

原帖地址:【求助】80分,#3点WA了,DFS+BFS

代码如下:

#include <cstdio>

#include <array>
#include <queue>
#include <set>

std::array<bool, 100005> kIsVisited;
std::array<std::multiset<int>, 100005> kGraph;
std::queue<int> kDfsAndBfsQueue;

bool Input(int* /* n */);
void RunDfsAndOutput(int /* total_book_num */);
void Dfs(int /* starting_point */);
void Bfs(int /* starting_point */);

int main(void) {
  bool run(false);
  int n(0);
  kIsVisited.fill(false);

  run = Input(&n);

  if (run) {
    RunDfsAndOutput(n);
    std::putchar('\n');
    kIsVisited.fill(false);
    Bfs(1);
    std::putchar('\n');
  } else {
    std::printf("0\n0\n");
  }

  return 0;
}

bool Input(int* n) {
  int m(0);
  std::scanf("%d %d", n, &m);

  if (0 == n) {
    return false;
  } else {
    for (int i = 0; i < m; ++i) {
      int from_point(0), to_point(0);
      std::scanf("%d %d", &from_point, &to_point);
      kGraph[from_point].insert(to_point);
    }
  }

  return true;
}

void RunDfsAndOutput(int total_book_num) {
  for (int i = 1; i < total_book_num + 1; ++i) {
    Dfs(i);
    while (!kDfsAndBfsQueue.empty()) {
      std::printf("%d ", kDfsAndBfsQueue.front());
      kDfsAndBfsQueue.pop();
    }
  }
}

void Dfs(int starting_point) {
  if (kIsVisited[starting_point]) {
    return;
  }

  kIsVisited[starting_point] = true;
  kDfsAndBfsQueue.push(starting_point);

  if (kGraph[starting_point].empty()) {
    return;
  }

  for (auto iter = kGraph[starting_point].begin();
       iter != kGraph[starting_point].end(); ++iter) {
    Dfs(*iter);
  }
}

void Bfs(int starting_point) {
  kIsVisited[starting_point] = true;
  kDfsAndBfsQueue.push(starting_point);
  std::printf("%d ", starting_point);

  while (!kDfsAndBfsQueue.empty()) {
    int now_point(kDfsAndBfsQueue.front());
    kDfsAndBfsQueue.pop();

    for (auto iter = kGraph[now_point].begin();
         iter != kGraph[now_point].end(); ++iter) {
      if (!kIsVisited[*iter]) {
        kIsVisited[*iter] = true;
        std::printf("%d ", *iter);
        kDfsAndBfsQueue.push(*iter);
      }
    }
  }
}

这是改进过的代码,可能更好看一些[笑]

2020/10/3 17:25
加载中...