2. Core C++ Features and STL Usage
Mastering the powerful features of C++ and the Standard Template Library (STL) is essential for solving USACO problems effectively.
2.1. Data Types and Variables
Choosing the appropriate data type based on problem constraints is crucial, especially when dealing with large numbers.
int: Generally for integers within the range of -2 * 10^9 to 2 * 10^9.long long: For integers roughly in the range of -9 * 10^18 to 9 * 10^18. (Often needed)double: For floating-point numbers.bool: For true/false values.
2.2. Deeper Dive into I/O Optimization
The I/O optimization code introduced on Page 1 is critical for quickly processing large datasets. Without it, \'Time Limit Exceeded\' is a common issue.
#include <iostream> // or <bits/stdc++.h>
int main() {
// These two lines are almost always mandatory in competitive programming.
ios::sync_with_stdio(0);
cin.tie(0);
int T; // Number of test cases
cin >> T;
while (T--) {
int N;
cin >> N;
// ... problem logic
}
return 0;
}
2.3. Introduction to STL (Standard Template Library)
The STL provides powerful data structures and algorithms, making your code concise and efficient.
std::vector: Dynamic array. Can flexibly adjust its size.
std::vector<int> v = {1, 2, 3};
v.push_back(4); // [1, 2, 3, 4]
std::pair: Bundles two values into a single entity. Can be aliased with pii.pii coord = {10, 20}; // x=10, y=20
cout << coord.first << ", " << coord.second;
std::sort: Sorts arrays or vectors. Highly efficient.std::vector<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end()); // [1, 2, 5, 8]
std::map / std::set: Store key-value pairs or unique elements. Internally use balanced binary trees for efficient search, insertion, and deletion.