tatyam’s blog

(ノ) - ω - (ヾ)モチモチ

パフォを上げるためのテンプレートのおはなし

この記事は Competitive Programming (1) Advent Calendar 2019 13日目の記事です。*1

みなさん、テンプレート使ってますか?

テンプレートを使うとたくさんの良いことがあります

  • プログラムを書くことに使う脳のリソースが減る
  • コーディング量が減る
  • バグりにくくなる
  • FAが取りやすくなる

私は144行のテンプレートを使っています

えぇ…

まあ、こんなに多くする必要はありませんが(スニペットにもできますし)、おすすめテンプレートを紹介していきますね

★★★ - 常備したいテンプレート

#include <bits/stdc++.h>
using namespace std;

い つ も の

C++の標準ライブラリを一行で一括でインクルードする - Qiita

using ll = long long;

基本的に int は使っていません

template<class T> using pq = priority_queue<T, vector<T>, greater<T>>;

Dijkstra 法で長いのは書きたくないので

using pll = pair<ll, ll>;

グラフとか、2つ組の入力とかに重宝する

const ll LINF = 0x1fffffffffffffff;

INF を作ったあと作ったのでこの名前 Long_INFinity : 4倍 してもオーバーフローしない数 (4倍することがあったため)
稀に int 型の INF も使う

#define overload4(_1, _2, _3, _4, name, ...) name
#define rep1(n) for(ll i = 0; i < (n); ++i)
#define rep2(i, n) for(ll i = 0; i < (n); ++i)
#define rep3(i, a, b) for(ll i = (a); i < (b); ++i)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)

これ使ったらやめられないね
可変長引数マクロ __VA_ARGS__... を展開する overload4()で5番目の名前を取り出せばそれぞれの引数の個数のマクロが出てくる

#define rrep(i, a, b) for(ll i = (b); i --> (a); )

Reverse_REPeat
これも可変長にしておくといい

# define each(i,...) for(auto&& i:__VA_ARGS__)

名前は for_each から
可変長引数にすることで間にカッコがあっても対応できる

#define all(i) begin(i), end(i)

sort(all(v)); reverse(all(v)); とかたくさん使う
これも可変長にしておくといい

template<class T> bool chmin(T &a, const T &b){ if(a > b){ a = b; return 1; } else return 0; }
template<class T> bool chmax(T &a, const T &b){ if(a < b){ a = b; return 1; } else return 0; }

たくさんのとこで使う 特に Dijkstra, BFS あたりで便利

template<class T> ll sum(const T& a){ return accumulate(all(a), 0LL); }

long long 型 で合計を求める
可変長all()を使う場合は #define する

template<class T> auto min(const T& a){ return *min_element(all(a)); }
template<class T> auto max(const T& a){ return *max_element(all(a)); }

たくさん使う

int scan(){ return getchar(); }
void scan(int& a){ scanf("%d", &a); }
void scan(unsigned& a){ scanf("%u", &a); }
void scan(long long& a){ scanf("%lld", &a); }
void scan(unsigned long long& a){ scanf("%llu", &a); }
void scan(char& a){ do{ a = getchar(); }while(a == ' ' || a == '\n'); }
void scan(float& a){ scanf("%f", &a); }
void scan(double& a){ scanf("%lf", &a); }
void scan(long double& a){ scanf("%Lf", &a); }
void scan(vector<bool>& a){ for(unsigned i = 0; i < a.size(); i++) { int b; scan(b); a[i] = b; } }
void scan(char a[]){ scanf("%s", a); }
void scan(string& a){ cin >> a; }
template<class T> void scan(vector<T>&);
template<class T> void scan(deque<T>&);
template<class T, size_t size> void scan(array<T, size>&);
template<class T, class L> void scan(pair<T, L>&);
template<class T, size_t size> void scan(T(&)[size]);
template<class T> void scan(vector<T>& a){ for(auto& i : a) scan(i); }
template<class T> void scan(deque<T>& a){ for(auto& i : a) scan(i); }
template<class T, size_t size> void scan(array<T, size>& a){ for(auto& i : a) scan(i); }
template<class T, class L> void scan(pair<T, L>& p){ scan(p.first); scan(p.second); }
template<class T, size_t size> void scan(T (&a)[size]){ for(auto& i : a) scan(i); }
template<class T> void scan(T& a){ cin >> a; }
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){ scan(head); in(tail...); }
void print(){ putchar(' '); }
void print(bool a){ printf("%d", a); }
void print(int a){ printf("%d", a); }
void print(unsigned a){ printf("%u", a); }
void print(long long a){ printf("%lld", a); }
void print(unsigned long long a){ printf("%llu", a); }
void print(char a){ printf("%c", a); }
void print(char a[]){ printf("%s", a); }
void print(float a){ printf("%.15f", a); }
void print(double a){ printf("%.15f", a); }
void print(long double a){ printf("%.15Lf", a); }
void print(const string& a){ for(auto&& i : a) print(i); }
template<class T> void print(const vector<T>&);
template<class T, size_t size> void print(const array<T, size>&);
template<class T, class L> void print(const pair<T, L>& p);
template<class T, size_t size> void print(const T (&)[size]);
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T> void print(const deque<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size>& a){ print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L>& p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> void print(const T (&a)[size]){ print(a[0]); for(auto i = a; ++i != end(a); ){ putchar(' '); print(*i); } }
template<class T> void print(const T& a){ cout << a; }
int out(){ putchar('\n'); return 0; }
template<class T> int out(const T& t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }

な が い
可変引数で、vectorとかを展開し、scanf/printf を使って入出力をやってくれる関数
これが一番便利だと思います(?) return out(-1); とかできるように out() の返り値は 0

★★ - あると便利なテンプレート

using ld = long double;
using ull = unsigned long long;
using uint = unsigned int;
using pii = pair<int, int>;
using pdd = pair<double, double>;
using tuplis = array<ll, 3>;

最近は double を使わず全部 ld にしてる
tuplis の名前は tuple<int, int, int> からきている

#define vec(type,name,...) vector<type> name(__VA_ARGS__)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))

vector の省略宣言

#define INT(...) int __VA_ARGS__; in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__; in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__; in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__; in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__; in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__; in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; in(__VA_ARGS__)
#define VEC(type,name,size) vector<type> name(size); in(name)
#define VV(type, name, h, w) vector<vector<type>> name(h, vector<type>(w)); in(name)

宣言と入力を両方やってくれるマクロ
とっても便利

template<class T> ld dsum(const T& a){ return accumulate(all(a), 0.0L); }

long double 型で合計を求める関数

const int INF = 0x3fffffff;
const ll MINF = 0x7fffffffffff;
const ld DINF = numeric_limits<ld>::infinity();
const int MOD = 1000000007;
const int MODD = 998244353;
const ld EPS = 1e-9;
const ld PI = 3.1415926535897932;

INF : int 型 の INF 2倍してもオーバーフローしない MINF : フローあたりで欲しくなった INF と LINF の中間 DINF : long double の INF (double は使わないので) MOD : いつもの MODD : いつもの EPS : だいたいこれくらいあれば大丈夫 PI : 幾何で使う

const ll four[] = {0, 1, 0, -1, 0};
const ll eight[] = {0, 1, 1, 0, -1, -1, 1, -1, 0};

グリッド上の探索に使う

ll gcd(ll a, ll b){ while(b){ ll c = b; b = a % b; a = c; } return a; }
ll lcm(ll a, ll b){ if(!a || !b) return 0; return a * b / gcd(a, b); }

AtCoderC++17 が追加されるまでの命

ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }

桁DPとか、整数問題に使う

vector<pll> factor(ull x){ vector<pll> ans; for(ll i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ll i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }

たまに使うやつ(速さ重視)

int first(bool i = true){ return out(i?"first":"second"); }
int yes(bool i = true){ return out(i?"yes":"no"); }
int Yes(bool i = true){ return out(i?"Yes":"No"); }
int No(){ return out("No"); }
int YES(bool i = true){ return out(i?"YES":"NO"); }
int NO(){ return out("NO"); }
int Yay(bool i = true){ return out(i?"Yay!":":("); }
int possible(bool i = true){ return out(i?"possible":"impossible"); }
int Possible(bool i = true){ return out(i?"Possible":"Impossible"); }
int POSSIBLE(bool i = true){ return out(i?"POSSIBLE":"IMPOSSIBLE"); }
void Case(ll i){ printf("Case #%lld: ", i); }

増え続けてるやつ
return Yes(); とか return No(); とかできるとうれしい

★ - スニペットにしたいテンプレート

sort(all(<#name#>));

sort はよく使うので 思考に追いつくために

return out(<#outputs#>);
return Yes(<#result#>);

これもちょっと長い

rep(4){
    ll x2 = x + four[i], y2 = y + four[i + 1];
    if(x2 < 0 || h <= x2 || y2 < 0 || w <= y2) continue;
    
}

グリッド上の探索に

ll ok = <#0#>, ng = <#100000000#>;
while(abs(ok - ng) > 1){
    ll cen = (ok + ng) / 2;
    
    if(<#ok#>) ok = cen;
    else ng = cen;
}

二分探索

template<class T>
struct PartialSum{
    vector<T> data;
    PartialSum(const vector<T>& v): data(v.size() + 1){
        for(ll i = 0; i < v.size(); i++) data[i + 1] = data[i] + v[i];
    }
    T get(ll l, ll r) const {
        return data[r] - data[l];
    }
    T operator[](ll at) const { return data[at]; }
};

累積和

template<class T>
struct PartialSum2D{
    vector<vector<T>> data;
    PartialSum2D(const vector<vector<T>>& v): data(v.size() + 1, vector<T>(v[0].size() + 1)){
        for(ll i = 0; i < v.size(); i++) for(ll j = 0; j < v[i].size(); j++) data[i + 1][j + 1] = data[i][j + 1] + v[i][j];
        for(ll i = 0; i < v.size(); i++) for(ll j = 0; j < v[i].size(); j++) data[i + 1][j + 1] += data[i + 1][j];
    }
    T get(ll x1, ll x2, ll y1, ll y2) const {
        return data[x2][y2] + data[x1][y1] - data[x1][y2] - data[x2][y1];
    }
    vector<T>& operator[](ll at) const { return data[at]; }
};

2次元累積和
特にこれは頭使うからstructにしておくといい

github.com

Modint

*1:12/13は素数大富豪の日ですね!