【求助】80分,#3点WA了,DFS+BFS
查看原帖
【求助】80分,#3点WA了,DFS+BFS
121479
聪明的猪楼主2020/10/1 16:40

代码如下:

#include <cstdio>

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

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

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

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

  Input(&n);
  RunDfsAndOutput(n);
  std::putchar('\n');

  kIsVisited.fill(false);
  kIsVisited[1] = true;
  kDfsAndBfsQueue.push(1);
  RunBfsAndOutput(n);

  return 0;
}

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

  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);
  }
}

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 RunBfsAndOutput(int total_book_num) {
  std::printf("1 ");
  Bfs();
  for (int i = 1; i < total_book_num + 1; ++i) {
    if (!kIsVisited[i]) {
      std::printf("%d ", i);
    }
  }
  std::printf("\n");
}

void Bfs(void) {
  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);
      }
    }
  }
}

蒟蒻代码,dalao轻喷[可怜]

2020/10/1 16:40
加载中...