关于在main函数里定义函数
  • 板块学术版
  • 楼主Infter
  • 当前回复6
  • 已保存回复6
  • 发布时间2023/4/30 07:56
  • 上次更新2023/10/23 17:11:52
查看原帖
关于在main函数里定义函数
386547
Infter楼主2023/4/30 07:56

我在 atcoder beginner contest 300\text{atcoder beginner contest 300} 的 D\text D 题的题解中发现了这样一段代码,我看它的调用好像类似函数一样,有dalao能帮我解释一下吗。

ABC300-Editorial-D

代码

auto ok = [&](int i, int j) { return 0 <= i and i < H and 0 <= j and j < W; };
  auto test = [&](int i, int j, int d) {
    for (auto& x : vector{+d, -d}) {
      for (auto& y : vector{+d, -d}) {
        int s = i + x, t = j + y;
        if (!ok(s, t) or g[s][t] != '#') return false;
      }
    }
    return true;
  };

完整代码

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
  int H, W;
  cin >> H >> W;
  vector<string> g(H);
  for (auto& x : g) cin >> x;

  auto ok = [&](int i, int j) { return 0 <= i and i < H and 0 <= j and j < W; };
  auto test = [&](int i, int j, int d) {
    for (auto& x : vector{+d, -d}) {
      for (auto& y : vector{+d, -d}) {
        int s = i + x, t = j + y;
        if (!ok(s, t) or g[s][t] != '#') return false;
      }
    }
    return true;
  };

  int N = min(H, W);
  vector<int> ans(N + 1);
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (g[i][j] != '#') continue;
      if (test(i, j, 1)) {
        int d = 1;
        while (test(i, j, d + 1)) d++;
        ans[d]++;
      }
    }
  }
  for (int i = 1; i <= N; i++) cout << ans[i] << " \n"[i == N];
}

2023/4/30 07:56
加载中...