← На главную

Основные приёмы Python и C++

Часто используемые конструкции и методы для олимпиадного программирования

Описание
Базовый ввод/вывод
n = int(input())
a, b = map(int, input().split())
arr = list(map(int, input().split()))
print(n, a, b, arr)
int n, a, b;
cin >> n >> a >> b;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
cout << n << " " << a << " " << b << endl;
Быстрый ввод/вывод
(для больших объёмов данных)
import sys
data = sys.stdin.read().split()
n = int(data[0])
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
Чтение из файла и запись в файл
with open('.in', 'r') as f:
    n = int(f.readline())
    A = list(map(int, f.readline().split()))

with open('.out', 'w') as f:
    f.write(f"{z}\n")
#include <fstream>
ifstream fin(".in");
ofstream fout(".out");

int n;
fin >> n;
fout << n << "\n";
Условный оператор
if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")
if (x > 0) {
    cout << "positive";
} else if (x == 0) {
    cout << "zero";
} else {
    cout << "negative";
}
Циклы (for, while)
for i in range(n):
    print(i)

while x > 0:
    x -= 1
for (int i = 0; i < n; i++) {
    cout << i;
}

while (x > 0) {
    x--;
}
Массивы / векторы
arr = [1, 2, 3]
arr.append(4)          # добавление
arr.sort()             # сортировка
len(arr)               # длина
vector<int> arr = {1, 2, 3};
arr.push_back(4);      // добавление
sort(arr.begin(), arr.end()); // сортировка
arr.size();            // длина
Работа со строками
s = "hello"
s[0]                 # доступ
s.upper()            # методы
len(s)               # длина
s.split()            # разделение
string s = "hello";
s[0];                // доступ
toupper(s[0]);       // методы
s.length();          // длина
stringstream ss(s);
ss >> part;          // разделение
Сортировка массива
arr.sort()                    # по возрастанию
arr.sort(reverse=True)        # по убыванию
arr.sort(key=lambda x: x[1])  # по ключу
sort(arr.begin(), arr.end());                     // по возрастанию
sort(arr.begin(), arr.end(), greater<int>());    // по убыванию
sort(arr.begin(), arr.end(), [](int a, int b) {
    return a > b;
});
Бинарный поиск
import bisect
pos = bisect.bisect_left(arr, x)   # первый >= x
pos = bisect.bisect_right(arr, x)  # первый > x
int pos = lower_bound(arr.begin(), arr.end(), x) - arr.begin(); // первый >= x
int pos = upper_bound(arr.begin(), arr.end(), x) - arr.begin(); // первый > x
Очередь с приоритетом (куча)
import heapq
heapq.heappush(heap, x)       # добавить
min_val = heapq.heappop(heap) # минимум
# max heap: heapq.heappush(heap, -x)
priority_queue<int> pq;  // max heap
pq.push(x);
int max_val = pq.top();
pq.pop();

// min heap:
priority_queue<int, vector<int>, greater<int>> pq;
Множество (set)
s = set()
s.add(x)        # добавление
if x in s:      # проверка
s.remove(x)     # удаление
unordered_set<int> s;
s.insert(x);           // добавление
if (s.count(x))        // проверка
s.erase(x);            // удаление
Словарь (ассоциативный массив)
d = {}
d[key] = value
if key in d:
    val = d[key]
for k, v in d.items():
    print(k, v)
unordered_map<int, int> mp;
mp[key] = value;
if (mp.count(key))
    int val = mp[key];
for (auto [k, v] : mp) {
    cout << k << " " << v;
}
Стек и очередь
from collections import deque
stack = []
stack.append(x)     # push
x = stack.pop()     # pop

queue = deque()
queue.append(x)     # push
x = queue.popleft() # pop
stack<int> st;
st.push(x);     // push
x = st.top();   // top
st.pop();       // pop

queue<int> q;
q.push(x);      // push
x = q.front();  // front
q.pop();        // pop
Создание двумерного массива (n×m, заполненного нулями)
a = [[0] * m for _ in range(n)]
vector<vector<int>> a(n, vector<int>(m, 0));
Чтение матрицы (n×m)
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
int n, m;
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m));
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        cin >> a[i][j];
Увеличение глубины рекурсии / настройка стека
import sys
sys.setrecursionlimit(10**6)
// Обычно не требуется,
// но для глубокой рекурсии:
// g++ -Wl,--stack,16777216 file.cpp
Генерация всех перестановок
from itertools import permutations

for perm in permutations(arr):
    print(perm)
#include <algorithm>
do {
    for (int x : arr) cout << x << " ";
    cout << "\n";
} while (next_permutation(arr.begin(), arr.end()));
Запуск внешней программы и получение вывода
import subprocess
result = subprocess.run(['main.exe'], 
                       input=s, 
                       text=True, 
                       capture_output=True)
ans = int(result.stdout.strip())
// system() — простой способ
system("main.exe < input.txt > output.txt");
// Чтение результата из файла
Побитовые операции
x & y    # побитовое И
x | y    # побитовое ИЛИ
x ^ y    # побитовое XOR
~x       # инверсия
x << k   # сдвиг влево
x >> k   # сдвиг вправо
x & y    // побитовое И
x | y    // побитовое ИЛИ
x ^ y    // побитовое XOR
~x       // инверсия
x << k   // сдвиг влево
x >> k   // сдвиг вправо