0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【AtCoder】ラムダ式

0
Last updated at Posted at 2024-05-22

ラムダ関数とは

main関数内でラムダ関数と呼ばれる関数を定義することができる。ラムダ関数を定義することで、それより前に定義されたmain関数内の変数や関数も使用することができる。つまり、ラムダ関数を使うことで、グローバル変数にすることによる手間がなくなるので便利である。ただしその際には、キャプチャを指定しなければいけないので注意するべし。

例題

ABC260B - Better Students Are Needed!

下記は、ラムダ関数を使わない実装例である

#include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;
#define rep(i, n) for (int i = 0; i < n; i++)

// main関数から切り出された変数や関数
int N;
vector<bool> passed;
vector<P> make_unpassed_list(vector<int> &score) {
  vector<P> res;
  rep(i, N) {
    if (!passed[i]) res.emplace_back(-score[i], i);
  }
  return res;
}
void f(vector<P> L, int cap) {
  sort(L.begin(), L.end());
  rep(i, cap) {
    auto [_, j] = L[i];
    passed[j] = true;
  }
}

int main() {
  int X, Y, Z;
  cin >> N >> X >> Y >> Z;
  vector<int> A(N), B(N), C(N);
  rep(i, N) cin >> A[i];
  rep(i, N) cin >> B[i];
  rep(i, N) C[i] = A[i] + B[i];
  passed = vector<bool>(N, false);
  
  f(make_unpassed_list(A), X);
  f(make_unpassed_list(B), Y);
  f(make_unpassed_list(C), Z);
  
  rep(i, N) {
    if (passed[i]) cout << i + 1 << endl;
  }
}

ラムダ関数を使うと下記のようになる。

#include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;
#define rep(i, n) for (int i = 0; i < n; i++)

int main() {
  int N, X, Y, Z;
  cin >> N >> X >> Y >> Z;
  vector<int> A(N), B(N), C(N);
  rep(i, N) cin >> A[i];
  rep(i, N) cin >> B[i];
  rep(i, N) C[i] = A[i] + B[i];
  vector<bool> passed(N, false);
  // ラムダ関数
  auto make_unpassed_list = [&](vector<int> &score) {
    vector<P> res;
    rep(i, N) {
      if (!passed[i]) res.emplace_back(-score[i], i);
    }
    return res;
  };
  // ラムダ関数
  auto f = [&](vector<P> L, int cap) {
    sort(L.begin(), L.end());
    rep(i, cap) {
      auto [_, j] = L[i];
      passed[j] = true;
    }
  };
  
  f(make_unpassed_list(A), X);
  f(make_unpassed_list(B), Y);
  f(make_unpassed_list(C), Z);
  
  rep(i, N) {
    if (passed[i]) cout << i + 1 << endl;
  }
}

参考

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?