7K12 blog

猫でも分かるアルゴリズム解説

STL一覧

int nyaa = 0; // piyo は古い
  • インデックスの計算(配列のサイズは 1-index)

インデックスの引き算
f:id:tkr987:20220410202709p:plain
インデックスの足し算
f:id:tkr987:20220410204938p:plain

  • 値を範囲に収める
#include <bits/stdc++.h>

int main()
{
	long long x = -15;
	x = std::clamp(x, 0ll, LLONG_MAX);
	std::cout << x << std::endl;
	return 0;
}

output
0

  • 多次元 array 初期化
#include <bits/stdc++.h>
// 入れ子になるのでサイズの順番に注意 dp[1000][10][1]
std::array<std::array<std::array<long long, 2>, 11>, 1001> dp;

int main()
{
	std::cout << dp[1000][10][1] << std::endl;
	dp[1000][10][1] = 9;
	std::cout << dp[1000][10][1] << std::endl;
	return 0;
}

output
0
9

#include <bits/stdc++.h>

void Print(std::vector<std::vector<int>>& v)
{
	for (int y = 0; y < 3; y++) for (int x = 0; x < 5; x++)
	{
		(x != 4) ? std::cout << v[y][x] << " " : std::cout << v[y][x] << std::endl;
	}
}

int main()
{
	std::vector<std::vector<int>> v1(3, std::vector<int>(5, 2));
	Print(v1);
	std::cout << "========" << std::endl;
	std::vector<std::vector<int>> v2;
	v2.assign(3, std::vector<int>(5, 2));
	Print(v2);
	return 0;
}

output
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
========
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2

  • 文字のインクリメント処理
#include <bits/stdc++.h>

int main(void)
{
	for (int i = 'a'; i <= 'z'; i++) std::cout << char(i) << " "; std::cout << std::endl;
	for (char c = 'a'; c <= 'z'; c++) std::cout << c << " "; std::cout << std::endl;
	return 0;
}

output
a b c d e f g h i j k l m n o p q r s t u v w x y z
a b c d e f g h i j k l m n o p q r s t u v w x y z

  • ソート(pair)
#include <bits/stdc++.h>

auto NyaaSort = [](const std::pair<int, int>& l, const std::pair<int, int>& r)
{	// 降順は演算子>, 昇順は演算子<, if順の優先でソートされる
	if (l.second != r.second) return l.second > r.second;
	return l.first < r.first;
};

int main(void)
{
	std::vector<std::pair<int,int>> nyaa = 
	{ {100,100}, {200,200}, {999,300}, {888,300}, {777,300} };

	sort(nyaa.begin(), nyaa.end(), NyaaSort);
	for (auto e : nyaa) std::cout << e.first << "|" << e.second << std::endl;
	return 0;
}

output
777|300
888|300
999|300
200|200
100|100

  • ソート(tuple)
#include <bits/stdc++.h>

auto NyaaSort = [](const std::tuple<int, int, int>& l, const std::tuple<int, int, int>& r)
{	// 降順は演算子>, 昇順は演算子<, if順の優先でソートされる
	auto [l1, l2, l3] = l; auto [r1, r2, r3] = r;
	if (l2 != r2) return l2 > r2;
	if (l3 != r3) return l3 > r3;
	return l1 < r1;
};

int main(void)
{
	std::vector<std::tuple<int,int,int>> nyaa = 
	{ {100,100, 100}, {200,200,200}, {999,300,110}, {888,300,120}, {777,300,130} };

	sort(nyaa.begin(), nyaa.end(), NyaaSort);
	for (auto [a,b,c] : nyaa) std::cout << a << "|" << b << "|" << c << std::endl;
	return 0;
}

output
777|300|130
888|300|120
999|300|110
200|200|200
100|100|100