diff --git a/NQueens.py b/NQueens.py new file mode 100644 index 0000000..c37d79a --- /dev/null +++ b/NQueens.py @@ -0,0 +1,56 @@ +def solve_n_queens(n: int): + res = [] + cols, diag1, diag2 = set(), set(), set() + board = [["."] * n for _ in range(n)] + + def backtrack(r: int): + if r == n: + res.append(["".join(row) for row in board]) + return + for c in range(n): + if c in cols or (r - c) in diag1 or (r + c) in diag2: + continue + cols.add(c); diag1.add(r - c); diag2.add(r + c) + board[r][c] = "Q" + backtrack(r + 1) + board[r][c] = "." + cols.remove(c); diag1.remove(r - c); diag2.remove(r + c) + + backtrack(0) + return res + + +def count_n_queens(n: int) -> int: + """ + Return the number of solutions using bitmasks (fast). + Columns, main- and anti-diagonals encoded as bitsets. + """ + full = (1 << n) - 1 + + def dfs(cols: int, d1: int, d2: int) -> int: + if cols == full: + return 1 + free = full & ~(cols | d1 | d2) + total = 0 + while free: + bit = free & -free + free -= bit + total += dfs( + cols | bit, + (d1 | bit) << 1 & full, + (d2 | bit) >> 1 + ) + return total + + return dfs(0, 0, 0) + +if __name__ == "__main__": + n = 4 + sols = solve_n_queens(n) + print(f"{n}-Queens: {len(sols)} solutions\n") + for i, b in enumerate(sols, 1): + print(f"Solution {i}:") + print("\n".join(b)) + print() + + print("Count via bitmasks:", count_n_queens(n)) \ No newline at end of file diff --git a/lru_cache.cpp b/lru_cache.cpp new file mode 100644 index 0000000..34c4ef5 --- /dev/null +++ b/lru_cache.cpp @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class LRUCache { + using Node = pair; + int cap; + list dq; + unordered_map::iterator> pos; + + void touch(list::iterator it) { + dq.splice(dq.begin(), dq, it); + } + void evict_if_needed() { + if ((int)dq.size() > cap) { + auto [k,_] = dq.back(); + pos.erase(k); + dq.pop_back(); + } + } +public: + explicit LRUCache(int capacity) : cap(capacity) { + if (cap <= 0) throw invalid_argument("capacity must be positive"); + } + + int get(int key) { + auto it = pos.find(key); + if (it == pos.end()) return -1; + touch(it->second); + return it->second->second; + } + + void put(int key, int value) { + auto it = pos.find(key); + if (it != pos.end()) { + it->second->second = value; + touch(it->second); + } else { + dq.emplace_front(key, value); + pos[key] = dq.begin(); + evict_if_needed(); + } + } +}; + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int Q; + if (!(cin >> Q)) return 0; + int capacity; + if (!(cin >> capacity)) return 0; + LRUCache cache(capacity); + + string op; + for (int i = 0; i < Q; ++i) { + if (!(cin >> op)) break; + if (op == "GET") { + int k; cin >> k; + cout << cache.get(k) << '\n'; + } else if (op == "PUT") { + int k, v; cin >> k >> v; + cache.put(k, v); + } else { + string line; getline(cin, line); + } + } + return 0; +} \ No newline at end of file