This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/2_General/Macros.md
2020-06-16 14:05:15 -04:00

2.2 KiB

id title author
macros C++ Macros Benjamin Qi

Shortening code and making it (un?)readable.

Introduction

My Template

Some comments about specific parts:

Pairs

typedef pair<int,int> pi;

#define mp make_pair
#define f first
#define s second

Pretty annoying to keep typing first and second (especially if you have nested pairs ...)

Vectors

typedef vector<int> vi; 

#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)

It's generally a good idea to convert a size to a signed integer before doing anything with it to avoid cases like the following.

vi x; 
cout << x.size()-1 << "\n"; // 18446744073709551615
cout << sz(x)-1 << "\n"; // -1

all(v) makes sorting part or all of a vector a bit shorter.

vi v = {2,4,1,5,3};
sort(1+all(v)); // {2,1,3,4,5}
sort(all(v)); // {1,2,3,4,5}

Constants

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);

10^9+7 is a prime that appears quite frequently in programming contests. Interestingly, (10^9+7-1)/2=5\cdot 10^8+3 is also prime. On the other hand, 998244353-1 is divisible by 2^{23}, which is useful for NTT.

Most USACO problems satisfy N\le 2\cdot 10^5.

RNG

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

See neal's blog about why rand() is bad. Uuse rng() instead.

ckmin

template<class T> bool ckmin(T& a, const T& b) { 
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }

See negCyc for an example of usage.