# =============================
#  Thuật toán dạng PRINT CODE
# =============================

tknp = """
def binary_search(a, target):
    l, r = 0, len(a) - 1
    while l <= r:
        mid = (l + r) // 2
        if a[mid] == target: return mid
        if a[mid] < target: l = mid + 1
        else: r = mid - 1
    return -1
"""

sapxep = """
def quicksort(a):
    if len(a) <= 1: return a
    pivot = a[len(a)//2]
    left  = [x for x in a if x < pivot]
    mid   = [x for x in a if x == pivot]
    right = [x for x in a if x > pivot]
    return quicksort(left) + mid + quicksort(right)
"""

snt = """
def eratosthenes(n):
    isprime = [True]*(n+1)
    isprime[0] = isprime[1] = False
    for i in range(2, int(n**0.5)+1):
        if isprime[i]:
            for j in range(i*i, n+1, i):
                isprime[j] = False
    return [i for i in range(n+1) if isprime[i]]
"""

bfs = """
from collections import deque

def bfs_shortest(grid, start, end):
    rows, cols = len(grid), len(grid[0])
    q = deque([(start[0], start[1], 0)])
    visited = set([start])

    while q:
        r, c, d = q.popleft()
        if (r, c) == end: return d
        
        for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and (nr,nc) not in visited and grid[nr][nc] == 0:
                visited.add((nr,nc))
                q.append((nr,nc,d+1))
    return -1
"""

loang = """
def flood_fill(grid, r, c, new_color):
    old = grid[r][c]
    if old == new_color: return
    rows, cols = len(grid), len(grid[0])

    def dfs(x, y):
        if x<0 or x>=rows or y<0 or y>=cols: return
        if grid[x][y] != old: return
        grid[x][y] = new_color
        dfs(x+1,y); dfs(x-1,y); dfs(x,y+1); dfs(x,y-1)

    dfs(r, c)
"""

dp = """
def longest_increasing_subsequence(a):
    n = len(a)
    dp = [1]*n
    for i in range(n):
        for j in range(i):
            if a[j] < a[i]:
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)
"""

matran = """
def read_matrix_from_file(path):
    matrix = []
    with open(path, "r") as f:
        for line in f:
            nums = list(map(int, line.strip().split()))
            matrix.append(nums)
    return matrix
"""

__all__ = [
    "tknp",
    "sapxep",
    "snt",
    "bfs",
    "loang",
    "dp",
    "matran"
]
