Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions NQueens.py
Original file line number Diff line number Diff line change
@@ -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))
74 changes: 74 additions & 0 deletions lru_cache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include <iostream>
#include <list>
#include <unordered_map>
#include <string>
#include <stdexcept>
#include <bits/stdc++.h>
using namespace std;

class LRUCache {
using Node = pair<int,int>;
int cap;
list<Node> dq;
unordered_map<int, list<Node>::iterator> pos;

void touch(list<Node>::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;
}