社区讨论

40分求助,dfs记忆化搜索,5 - 10 WA

P4017最大食物链计数参与者 3已保存回复 7

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
7 条
当前快照
1 份
快照标识符
@lo2w22ma
此快照首次捕获于
2023/10/23 20:43
2 年前
此快照最后确认于
2023/10/23 20:43
2 年前
查看原帖
如题,代码如下(未删除调试输出,代码是Better Align自动格式化的)。
CPP
// basic/functional headers
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
// debug headers
#include <stdexcept>
// data structure headers
#include <array>
#include <string>
#include <vector>
// macros n' defines
#define INT_INF 2147483648
#define N_INT_INF -2147483649
#define mod 80112002
// namespaces
using namespace std;
// aliases
using lld = long long int;
using ulld = unsigned long long int;

// vars, structs, classes
struct animal {
  vector<lld> eat_rlt;
  bool pdt = false;
};
lld types, tot_rlt, temp_1, temp_2, ans = 0;
array<animal, 5100> animals;
array<lld, 5100> notebook;
array<bool, 5100> visited;

// fn declaration
void print_(lld k);
void nb_print();
lld mem_dfs(lld k);

// main fn start
int main() {
  cin >> types >> tot_rlt;
  // food chain input
  for (lld i = 1; i <= tot_rlt; i++) {
    cin >> temp_1 >> temp_2;
    animals.at(temp_1).pdt = true;
    animals.at(temp_2).eat_rlt.push_back(temp_1);
  }
  // dfs
  for (short i = 1; i <= types; i++) {
    cout << endl
         << "This one is: " << i << ", the size of its eat_rlt is "
         << animals.at(i).eat_rlt.size() << "." << endl;
    if (animals.at(i).pdt) {
      cout << "Not apex predator, next one." << endl;
      continue;
    } else {
      cout << "Apex predator, start dfs." << endl;
      ans += mem_dfs(i);
      cout << endl;
    }
  }
  // output answer
  cout << "answer is: ";
  cout << ans % mod;
  // return with 0
  return 0;
}
// main fn end

// fn
lld mem_dfs(lld k) { // mem_dfs
  // memory check
  if (visited.at(k)) {
    cout << "Visited, return noted val: " << notebook.at(k) << endl;
    return notebook.at(k);
  } else {
    cout << "New one, change visited to true." << endl;
    visited.at(k) = true;
    cout << "This one's eat_rlt: " << endl;
    print_(k);
  }
  // define tot_ways
  lld ways = 0;
  // edge return
  if (animals.at(k).eat_rlt.size() == 0) {
    cout << "Edge! Return 1." << endl;
    cout << "End! printing notebook." << endl;
    nb_print();
    return notebook.at(k) = 1;
  }
  // normal return
  else {
    for (short i = 0; i < animals.at(k).eat_rlt.size(); i++) {
      cout << "Now searching: " << animals.at(k).eat_rlt.at(i) << endl;
      ways += mem_dfs(animals.at(k).eat_rlt.at(i));
    }
  }
  cout << "End! printing notebook." << endl;
  nb_print();
  return notebook.at(k) = ways;
}

void print_(lld k) { // print k's eat_rlt
  if (animals.at(k).eat_rlt.size() == 0) {
    cout << "Nothing here.";
  }
  for (auto iter : animals.at(k).eat_rlt) {
    cout << iter << " ";
  }
  cout << endl;
}

void nb_print() { // print notebook
  for (short i = 1; i <= types; ++i) {
    cout << notebook.at(i) << " ";
  }
  cout << endl;
}

回复

7 条回复,欢迎继续交流。

正在加载回复...