blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
1f7598ede4e67512cc27c647b7bc04a6d4565106 | 981377660LMT/algorithm-study | /6_tree/经典题/后序dfs统计信息/换根dp/遍历树中特殊点/Tree_getTreeSubGraph-树的包含特殊点的子图.py | 1,159 | 3.546875 | 4 | # Tree_getTreeSubGraph-树中包含特殊点的导出子图
from typing import List, Tuple
INF = int(1e18)
def getTreeSubGraph(
n: int, rawTree: List[List[int]], specials: List[int]
) -> Tuple[List[List[int]], List[Tuple[int, int]], List[bool]]:
"""给定`原树`(无向图邻接表), 返回`子图(无向图邻接表), 子图中的边, 原图中每个点是否在子图中`."""
if len(special... |
4adb84cc4e672ae800af1bf2decab8f993ac53b5 | 981377660LMT/algorithm-study | /17_模式匹配/寻找子序列binarysearch.py | 399 | 3.609375 | 4 | # 是否存在子序列binarysearch 索引间隔相等
class Solution:
def solve(self, s):
b = [i for i, c in enumerate(s) if c == "b"]
i = [i for i, c in enumerate(s) if c == "i"]
for j in b:
for k in i:
if k > j:
if "binarysearch" in s[j :: k - j]:
... |
0f652965bf007d4c9ac0a6fcdb206d241b24db28 | 981377660LMT/algorithm-study | /20_杂题/Datatime.py | 4,386 | 3.65625 | 4 | from typing import Tuple
class DateTime:
_MONTH_DAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
@staticmethod
def from_int(x: int) -> "DateTime":
y = x * 400 // 146097 + 1
d = x - DateTime(y, 1, 1).to_int()
m = 1
while d >= 28:
k = DateTi... |
8f5b9dca5e77c8e477c713930567d94412eb3eeb | 981377660LMT/algorithm-study | /17_模式匹配/后缀数组/1698. 字符串的不同子字符串个数.py | 929 | 3.65625 | 4 | # 本质不同子串个数 = 所有子串个数 - 相同子串个数
from SA import useSA
def countDistinct(s: str) -> int:
"""给定一个字符串 s,返回 s 的不同子字符串的个数。
用所有子串的个数,减去相同子串的个数,就可以得到不同子串的个数。
计算后缀数组和高度数组。根据高度数组的定义,所有高度之和就是相同子串的个数。
https://leetcode-cn.com/problems/number-of-distinct-substrings-in-a-string/solution/on-hou-zhui-shu-zu-b... |
13e6ef01aa7be1a53a70838535023bf5be151eee | 981377660LMT/algorithm-study | /20_杂题/atc競プロ/AtCoder Beginner Contest/198/C - Compass Walking.py | 741 | 3.515625 | 4 | # 圆规行走
# 从原点出发 每次必须走到距离当前点为r的点(不必走到网格上的整点)
# 问最少走多少步能走到tr,tc
# r<=1e5 x,y<=1e5
# !注意不能bfs 会TLE 需要数学解法
# !计算(x,y)到原点距离后向上取整,特别地,对于距离小于r的,需要两步才能到。
from math import ceil
def compassWalk(r: int, tr: int, tc: int) -> int:
dist = (tr**2 + tc**2) ** 0.5
if dist < r:
return 2 # 折返
retu... |
f9c6dcc90e6d4e80b14412835e39b699ff87143e | 981377660LMT/algorithm-study | /11_动态规划/dp分类/路径dp/行和列分开dp/1632. 矩阵转换后的秩-行列并查集.py | 4,631 | 3.859375 | 4 | # https://leetcode.cn/problems/rank-transform-of-a-matrix/
# 1632. 矩阵转换后的秩
# 给你一个 m x n 的矩阵 matrix ,请你返回一个新的矩阵 answer ,
# 其中 answer[row][col] 是 matrix[row][col] 的秩。
# 每个元素的 秩 是一个整数,表示这个元素相对于其他元素的大小关系,它按照如下规则计算:
# 秩是从 1 开始的一个整数。
# 如果两个元素 p 和 q 在 同一行 或者 同一列 ,那么:
# 如果 p < q ,那么 rank(p) < rank(q)
# 如果 p == q ,那么 ra... |
5118891b08dd450cfb89785c282bcca647e6f9f0 | 981377660LMT/algorithm-study | /21_位运算/按位或/2044. 统计按位或能得到最大值的子集数目-counter滚动更新.py | 1,045 | 3.546875 | 4 | from typing import Counter, List
class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
"""统计按位或能得到最大值的子集数目"""
# counter滚动更新
dp = Counter({0: 1})
for num in nums:
for key, count in list(dp.items()):
dp[key | num] += count
... |
1e843753bea4403eb77963128db1d04c99e594f7 | 981377660LMT/algorithm-study | /19_数学/计算几何/圆形/两圆相交面积.py | 1,212 | 3.78125 | 4 | # 两圆相交面积
# https://tjkendev.github.io/procon-library/python/geometry/circles_intersection_area.html
from math import pi, atan2
# 两圆相交面积
def circles_intersection_area(x1: int, y1: int, r1: int, x2: int, y2: int, r2: int) -> float:
"""两圆相交面积"""
dd = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
... |
e5f5160f30abc0467e0e3f95b2c9fd8e3aae784d | 981377660LMT/algorithm-study | /20_杂题/atc競プロ/AtCoder Beginner Contest/259/B - Counterclockwise Rotation.py | 913 | 3.6875 | 4 | # 给定坐标(x, y)问绕原点逆时针旋转d角度后的坐标。
# 坐标为a'= a * cos d - y * sin d, g = a * sin d + y * cosd,可以用各种方法(诱导公式/旋转矩阵)推:
# !向量旋转
from math import cos, radians, sin
import sys
import os
from typing import Tuple
sys.setrecursionlimit(int(1e9))
input = lambda: sys.stdin.readline().rstrip("\r\n")
MOD = int(1e9 + 7)
de... |
04732f56997be20b8bc2ceac6684c90925c6d426 | 981377660LMT/algorithm-study | /23_设计类/设计文本编辑器/2689. Extract Kth Character From The Rope Tree.py | 950 | 3.53125 | 4 | # https://leetcode.cn/problems/extract-kth-character-from-the-rope-tree/
# 获取Rope的第K个字符
from typing import Optional
# Definition for a rope tree node.
class RopeTreeNode:
def __init__(self, len=0, val="", left=None, right=None):
self.len = len
self.val = val
self.left = left
... |
1b1030308d7e9282a032566d60e51b1f12e45895 | 981377660LMT/algorithm-study | /21_位运算/格雷码/1238. 循环码排列.py | 437 | 3.96875 | 4 | from typing import List
# 给你两个整数 n 和 start。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p
class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
return [start ^ i ^ (i >> 1) for i in range(2 ** n)]
print(Solution().circularPermutation(n=3, start=2))
# 输出:[2,6,7,5,4,0,1,3]
# 解释:这个排列... |
4ba416bc443732063d2757149c0541d6ee21b54c | 981377660LMT/algorithm-study | /22_专题/前缀与差分/差分数组/离散化/离散化模板-1331. 数组序号转换.py | 1,177 | 3.578125 | 4 | # https://leetcode.cn/problems/rank-transform-of-an-array/
"""给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。"""
from bisect import bisect_right
from typing import List
class Solution:
def arrayRankTransform1(self, arr: List[int]) -> List[int]:
"""离散+二分查询"""
allNums = sorted(set(arr))
re... |
b8de260edce783c65227ce6adc6dfee80569574a | 981377660LMT/algorithm-study | /22_专题/日程安排-扫描线+差分/2015_每个线段的平均高度-差分+扫描线.py | 1,822 | 3.53125 | 4 | from typing import List
from collections import defaultdict
# 将重叠区间内的所有大楼高度求平均值,返回这些区域可进行分段的大楼跨度及其高度平均值数组
# 且遇到楼层平均高度相同的相邻区间时要合并
# 1943. 描述绘画结果-扫描.py
# 1. 使用map记录每个分界处的 差分信息
# 2. 排序,遍历每个分界点,更新 pre/preSum/preCount
class Solution:
def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[Li... |
2abc3eda58ecfee7de0adc69143acad90c55bc4e | 981377660LMT/algorithm-study | /9_排序和搜索/经典题/自定义比较函数/数组组成最大数-拼接字典序最大.py | 920 | 4.25 | 4 | # 剑指 Offer 45. 把数组排成最小的数
from functools import cmp_to_key
from typing import List
# !给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
# 数组组成最大数(拼接最大序)
# cmp_to_key 将compare函数转换成key
def mergeSort(s1: str, s2: str) -> int:
"""拼接两个字符串,字典序最小"""
return -1 if s1 + s2 < s2 + s1 else 1
def toMax(nums: List[int]) -> ... |
dd1850300963c0c62ce1551e173f3f69211cd101 | 981377660LMT/algorithm-study | /6_tree/树的性质/树哈希/树的最小表示-树的括号表示.py | 1,738 | 3.765625 | 4 | # AcWing 157. 树形地铁系统(树的最小表示)
# 有n组数据,每个数据给两个树的dfs序,0表示向下走,1表示向上走,问这两个树是不是同构的。
# O(n^2)
# 如果两个字符串描述的探索路线可以视为同一个地铁系统的两种探索路线,则输出 same
from collections import deque
def check(s1: str, s2: str) -> bool:
"""两棵有根树是否同构(对应子树位置可以不同)
len(s1) == len(s2) <= 3000
如果两颗树是同构的,当且仅当 这两颗树的最小表示是相同的。
可以对... |
2aac46f82552d1c21e9ee107ec417b0444796d15 | 981377660LMT/algorithm-study | /22_专题/枚举/枚举分割点-前后缀分解/枚举分割点/acwing845. 数组中的最长山脉-子序列.py | 1,118 | 3.515625 | 4 | from typing import List
# 数组 A 中符合下列属性的任意`子序列` B 称为 “山脉”:
# B.length >= 3
# 先绝对单增后绝对单减
# 返回最长 “山脉” 的长度。
# 数组中求一个最长的山脉的长度,满足山脉中没有两个相邻的相同高度的点,且只有一个峰
# n<=1000
class Solution:
def longestMountain(self, arr: List[int]) -> int:
n = len(arr)
up = [0] * n
down = [0] * n
... |
de6378f101239d52c399e53d1291b84af868b941 | 981377660LMT/algorithm-study | /22_专题/implicit_graph/RangeFinder/Finder-fastset.py | 3,937 | 3.609375 | 4 | # 寻找前驱后继/区间删除
from typing import Optional
class Finder:
"""利用位运算寻找区间的某个位置左侧/右侧第一个未被访问过的位置.
初始时,所有位置都未被访问过.
"""
__slots__ = "_n", "_lg", "_seg"
@staticmethod
def _trailingZeros1024(x: int) -> int:
if x == 0:
return 1024
return (x & -x).bit_length... |
bc84f68a5a596fd5e9446378494c4b985d3171e7 | 981377660LMT/algorithm-study | /3_linkedList/2816. 翻倍以链表形式表示的数字-链表倒序处理技巧 - 递归.py | 1,071 | 4.0625 | 4 | # 2816. 翻倍以链表形式表示的数字-链表倒序处理技巧 - 递归
# 首先 dfs 到最深处,然后在 dfs 返回的时候进行元素处理,这样不就相当于倒序遍历链表了吗!
# https://leetcode.cn/problems/double-a-number-represented-as-a-linked-list/solutions/2385928/lian-biao-dao-xu-chu-li-ji-qiao-di-gui-b-0n1z/
# 给你一个 非空 链表的头节点 head ,表示一个不含前导零的非负数整数。
# 将链表 翻倍 后,返回头节点 head 。
from typing impo... |
9a4dc19dbacb00568e51016cfcb1e5e22cf01102 | 981377660LMT/algorithm-study | /19_数学/acwing专项训练/分解质因数/197. 阶乘分解-勒让德定理.py | 1,521 | 3.515625 | 4 | # 给定整数 N,试把阶乘 N! 分解质因数,按照算术基本定理的形式输出分解结果中的 pi 和 ci 即可。
# 3≤N≤1e6
"""
先把1-1000000中所有质数全部筛出来
然后统计每一个质数出现的次数,假设
当前统计的质数是P
P在N阶乘中出现的次数就是看1-N中所有数字
出现P因子的次数总和
根据勒让德定理就是 N//P + N//(P^2) + N//(p^3) + ......
"""
from collections import Counter
from typing import List
# def getPrimeFactors(n: int) -> Counter:... |
ee0b4dcabf37ed0a66f3ab90c534a0a993b3d752 | 981377660LMT/algorithm-study | /21_位运算/Fraction/166. 分数到小数.py | 1,004 | 4 | 4 | # 166. 分数到小数
# 将分数转换为小数,如果小数部分为循环小数,则将循环的部分括在括号内。
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
sb = []
a, b = numerator, denominator
if a == 0:
return "0"
if a > 0 ^ b > 0:
sb.append("-")
a, b = ... |
dcd2e07b88d286af6b15f6fb586d7dc1c66a363c | 981377660LMT/algorithm-study | /9_排序和搜索/二分/二分答案法/2064. 分配给商店的最多商品的最小值.py | 648 | 3.5 | 4 | from typing import List
from math import ceil
class Solution:
def minimizedMaximum(self, n: int, quantities: List[int]) -> int:
def check(mid):
res = 0
for num in quantities:
res += ceil(num / mid)
if res > n:
return Fa... |
b9f20191f6f07b00040001205366d4521eb9bea4 | 981377660LMT/algorithm-study | /7_graph/二分图/带权二分图的最大权匹配问题/6232. 最小移动总距离-scipy调库解法.py | 1,290 | 3.671875 | 4 | from typing import List
from scipy.optimize import linear_sum_assignment
INF = int(1e18)
class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
"""带权图最大权匹配
Args:
robot (List[int]): 机器人的位置
factory (List[List[int]]):... |
797fb5e4b44f2abe5c67ca7a0b9b2fba00dcd1e2 | 981377660LMT/algorithm-study | /7_graph/经典题/置换环/amidakuji鬼脚图/1-最少的横线构造amidakuji.py | 889 | 3.8125 | 4 | # 冒泡排序邻位交换 构造amidakuji的横线
from typing import List
def amidakuji(ends: List[int]) -> List[int]:
"""
冒泡排序构造amidakuji的横线
Args:
ends: 每个点最后的位置 (1-index)
Returns:
鬼脚图的横线,一共m条,从上往下表示.
lines[i] 表示第i条横线连接 line[i] 和 line[i]+1. (1-index)
"""
n = len(ends)
res ... |
80ad2061792f628aa52d21734d98a063ff785e33 | 981377660LMT/algorithm-study | /前端笔记/thirtysecondsofcode/python/python的typings/6_typeof.py | 406 | 3.65625 | 4 | from typing import Type
a = 3 # Has type 'int'
b = int # Has type 'Type[int]'
c = type(a) # Also has type 'Type[int]'
class User:
...
class BasicUser(User):
...
class ProUser(User):
...
class TeamUser(User):
...
# Accepts User, BasicUser, ProUser, TeamUser, ...
de... |
d6625afe8b1035a50a020e54e54f21961ed2ebe6 | 981377660LMT/algorithm-study | /0_字符串/字符串变换/917_仅仅反转字母 copy.py | 315 | 3.703125 | 4 | # 字母栈 倒序填充
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
alpha = [char for char in s if char.isalpha()]
print(alpha)
return ''.join([char if not char.isalpha() else alpha.pop() for char in s])
print(Solution().reverseOnlyLetters("a-bC-dEf-ghIj"))
|
0e5a352f139594f18f0a0229ea0d8c73b2287e29 | 981377660LMT/algorithm-study | /0_字符串/927. 三等分.py | 1,896 | 3.75 | 4 | from typing import List, Sequence
# !将数组分成 3 个非空的部分,使得所有这些部分表示相同的二进制值。
# 如果无法做到,就返回 [-1, -1]。
# 前导零也是被允许的,所以 [0,1,1] 和 [1,1] 表示相同的值。
# !如果要将数组进行三等分,那么每组中1的数目一定要相同
# https://leetcode.com/problems/three-equal-parts/discuss/1343709/2-clean-Python-linear-solutions
def useArrayHasher(nums: Sequence[int], mod... |
25130dfd65308dc8f8c036b6e348f0a6acfdb1a7 | 981377660LMT/algorithm-study | /22_专题/前缀与差分/差分数组/deltaDict离散化差分/Interval Painting.py | 1,184 | 3.75 | 4 | # 求至少走过target次的区间数
# if you walk right 2 times, then you walked on blocks [0, 1] and [1, 2] once each.
# If you walk left once, then you'd walk on block [1, 2] again.
# Return the number of blocks that's been walked on at least target number of times.
from collections import defaultdict
# 0 ≤ n ≤ 100,000 n为区间... |
706349073e3776da5137f0eed94fd623fec85d92 | 981377660LMT/algorithm-study | /12_贪心算法/经典题/2136. 全部开花的最早一天-操作系统优先级调度思想.py | 1,962 | 3.703125 | 4 | from typing import List
# https://leetcode-cn.com/problems/earliest-possible-day-of-full-bloom/comments/1323899
# 把 播种时间 看作 进程使用cpu的时间 ,
# 把 生长时间 看作 I/O设备工作的时间,
# 由于I/O型设备的处理速度比CPU慢得多,只有让I/O设备尽早地进行工作,
# cpu才能调度其他进程执行,这样会提升系统的整体效率。
# cpu先调度I/O时间长的进程先执行,
# 才能在I/O设备工作的时候尽可能的调度其他程序执行,这样最终的时间会更短
# 对照计算机系统结构的流水线作业,... |
dcc3f5db1dd1aaeaeda61d7acc5395ab137f0125 | 981377660LMT/algorithm-study | /22_专题/计算偏移量(同余分组)/2598. 执行操作后的最大 MEX.py | 762 | 3.796875 | 4 | # 2598. 执行操作后的最大 MEX
# !在一步操作中,你可以对 nums 中的任一元素加上或减去 value 。
# 数组的 MEX (minimum excluded) 是指其中数组中缺失的最小非负整数。
# 返回在执行上述操作 任意次 后,nums 的最大 MEX 。
from collections import Counter
from typing import List
class Solution:
def findSmallestInteger(self, nums: List[int], value: int) -> int:
modCounter =... |
072654de6d2555ddc9ef04e8dc2f6d691e0c502f | 981377660LMT/algorithm-study | /20_杂题/美团校园招聘笔试真题/0-python获取输入.py | 141 | 3.515625 | 4 | n = int(input())
for _ in range(n):
line = input()
print(line)
res = [0] * n
# 输出答案
for v in res:
print(v)
|
25f59cb34ce9cea635159c5713e5c6db5066b016 | 981377660LMT/algorithm-study | /14_并查集/经典题/维护到根节点距离/238. 银河英雄传说-维护到根节点距离的并查集 .py | 2,183 | 3.515625 | 4 | # 有 T 条指令,每条指令格式为以下两种之一:
# M i j,表示让第 i 号战舰所在列的全部战舰保持原有顺序,接在第 j 号战舰所在列的尾部。
# C i j,表示询问第 i 号战舰与第 j 号战舰当前是否处于同一列中,如果在同一列中,它们之间间隔了多少艘战舰。
class UnionFindArrayWithDist:
"""固定元素 维护距离的并查集"""
def __init__(self, n: int):
self.n = n
self.count = n
self.parent = list(range(n))
... |
accebf20a8b38eb27330f7ec76e02e9f5d7debae | 981377660LMT/algorithm-study | /19_数学/计算几何/圆形/最小圆覆盖.py | 2,550 | 4.125 | 4 | # 你需要用最少的原材料给花园安装一个 圆形 的栅栏,
# 使花园中所有的树都在被 围在栅栏内部(在栅栏边界上的树也算在内)。
# https://leetcode.cn/problems/erect-the-fence-ii/
# !最小圆覆盖 Welzl 算法(随机增量法)
# n<=3000
import random
from typing import List, Tuple, Union
EPS = 1e-8
def calCircle2(
x1: int, y1: int, x2: int, y2: int, x3: int, y3: int
) -> Union[T... |
a3ab4c17b0687d7dd4def1944823a7bf5ccebe76 | 981377660LMT/algorithm-study | /11_动态规划/编辑距离/6228. 距离字典两次编辑以内的单词.py | 1,239 | 3.5 | 4 | from typing import List
# 给你两个字符串数组 queries 和 dictionary 。
# 数组中所有单词都只包含小写英文字母,且长度都相同。
# 一次 编辑 中,你可以从 queries 中选择一个单词,
# !将任意一个字母修改成任何其他字母。
# 从 queries 中找到所有满足以下条件的字符串:不超过 两次编辑内,字符串与 dictionary 中某个字符串相同。
# 请你返回 queries 中的单词列表,这些单词距离 dictionary 中的单词 编辑次数 不超过 两次 。
# 单词返回的顺序需要与 queries 中原本顺序相同。
# !因为只能`修改`... |
c3df638e56056ebcb27d226c19f92b21bace5819 | 981377660LMT/algorithm-study | /0_数组/二维数组/泡泡堂/1267. 统计参与通信的服务器.py | 1,044 | 3.5 | 4 | from typing import List
# 如果两台服务器位于同一行或者同一列,我们就认为它们之间可以进行通信。
# 请你统计并返回能够与至少一台其他服务器进行通信的服务器的数量。
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
rowCounter = [0] * row
colCounter = [0] * col
for r in range(row):
... |
e877840a224b3dfb03508159fe6a4d043e3a0cc3 | 981377660LMT/algorithm-study | /19_数学/计算几何/直线/点到直线的投影坐标.py | 743 | 3.953125 | 4 | from typing import Tuple
def projection(line: Tuple[int, int, int, int], point: Tuple[int, int]) -> Tuple[float, float]:
"""点在直线上的投影坐标."""
x1, y1, x2, y2 = line
x3, y3 = point
dot = (x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1)
d2 = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5 #... |
897a94af55dfec8c3a91653919971ef5249e614c | 981377660LMT/algorithm-study | /16_滑动窗口/k重复字符子串词频统计/3.1695. 删除子数组的最大得分-无重复字符的最大和子串.py | 699 | 3.546875 | 4 | from typing import List
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
res = 0
curSum = 0
left, right = 0, 0
visited = set()
while right < len(nums):
if nums[right] not in visited:
curSum += nums[right]
... |
bfff31c518f73e1e9ffdab2b1839d8b4fd83fb76 | 981377660LMT/algorithm-study | /前端笔记/python/src/lambda.py | 625 | 3.828125 | 4 | def multiply():
return [lambda x: i * x for i in range(4)]
print([m(100) for m in multiply()])
# 首先需要注意的是multiply函数用生成式语法返回了一个列表,
# 列表中保存了4个Lambda函数,这4个Lambda函数会返回传入的参数乘以i的结果。需要注意的是这里有闭包(closure)现象,multiply函数中的局部变量i的生命周期被延展了,
# 由于i最终的值是3
# 方法改进:使用生成器,让函数获得i的当前值。
def multiply2():
for i in range(4... |
dd7911b57db719d347d9218e4c141a600c3feb5b | 981377660LMT/algorithm-study | /17_模式匹配/kmp/findAll.py | 516 | 3.984375 | 4 | from typing import List
def findAll(string: str, target: str) -> List[int]:
"""找到所有匹配的字符串起始位置"""
start = 0
res = []
while True:
pos = string.find(target, start)
if pos == -1:
break
else:
res.append(pos)
start = pos + 1
ret... |
f367439ec85dd1106ffd841d4bc9aa226dce49c0 | 981377660LMT/algorithm-study | /17_模式匹配/kmp/1668. 最大重复子字符串.py | 1,626 | 3.5 | 4 | # 最大重复子字符串
# 单词 word 的 最大重复值 是单词 word 在 sequence 中最大的重复值。
# 给你一个字符串 sequence 和 word ,请你返回 最大重复值 k。
from typing import List
def findAll(string: str, target: str) -> List[int]:
"""找到所有匹配的字符串起始位置"""
start = 0
res = []
while True:
pos = string.find(target, start)
if pos == ... |
64348003f974a39a63bac563c1e41f6cd3756b06 | 981377660LMT/algorithm-study | /20_杂题/atc競プロ/AtCoder Regular Contest/ARC145/A - AB Palindrome.py | 487 | 3.546875 | 4 | """
有一个长度为N的字符串S,
字符串中只有 A,B两种字符,
每次都可以将S中两个相邻的字符替换为AB。
问能否将S变成回文字符串。
分类讨论
https://zhuanlan.zhihu.com/p/548093657
"""
import sys
import os
sys.setrecursionlimit(int(1e9))
input = lambda: sys.stdin.readline().rstrip("\r\n")
MOD = 998244353
INF = int(4e18)
n = int(input())
s = input()
print("No" i... |
c3a63ab08448d3f734dc8fb3bdaaaad997d2bf0b | 981377660LMT/algorithm-study | /15_双指针/分类/头尾指针/取出字符的最小代价.py | 1,846 | 3.765625 | 4 | # 从一个单词中取一个字母所需要的代币数量,为该字母左边和右边字母数量之积
from functools import lru_cache
from collections import deque
from typing import Tuple
INF = int(1e12)
@lru_cache(None)
def calCost(need: Tuple[bool, ...]) -> int:
"""计算从两端取出所需字符的代价 deque"""
n = len(need)
queue = deque([i for i in range(n) if need[i]]... |
cbbce433a7c121bd7cb59fb2b29dbb2264812754 | 981377660LMT/algorithm-study | /6_tree/二分搜索树BST/285. 二叉搜索树中的中序后继.py | 1,085 | 3.765625 | 4 | # Definition for a binary tree node.
from itertools import chain, dropwhile, takewhile
from typing import Generator, Optional
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderSuccessor(self, root: 'TreeNode... |
cb870b48d5ac91d66ca7b63a3adfb679fb2cdaf4 | 981377660LMT/algorithm-study | /0_字符串/python数组比较与字符串比较.py | 569 | 3.515625 | 4 | import time
# !数组比较需要除以50-200的常数
res = 0.0
for _ in range(100000):
arr1 = [0] * 1000 + [1]
arr2 = [0] * 1000 + [2]
time1 = time.time()
tmp = arr1 < arr2
time2 = time.time()
res += time2 - time1
print(res) # 0.13074040412902832
# !字符串比较需要除以250-1000的常数
res = 0.0
for _ in range(... |
4db29a937057ad11ef726e496b6420a44fc07769 | 981377660LMT/algorithm-study | /22_专题/无限整数序列/400. 第 N 位数字.py | 1,897 | 3.625 | 4 | # 400. 第 N 位数字
# https://leetcode.cn/problems/nth-digit/
# 给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字。
def findNthDigit(n: int) -> int:
"""O(lgn)返回第n位数码, n从1开始."""
base, count = 1, 1
while True:
digitSum = count * 9 * base
if n > digitSum:
... |
2a313d0bc8e4989cd4aa52bb2adced33c6c44e5c | 981377660LMT/algorithm-study | /22_专题/计算贡献/891. 子序列宽度之和.py | 853 | 3.640625 | 4 | # 一个序列的 宽度 定义为该序列中最大元素和最小元素的差值。
# 返回 nums 的所有非空 子序列 的 宽度之和 。
# 1 <= nums.length <= 10^5
# 对数组进行排序
# 对每个数,统计他作为最大/最小值在多少个`取他`的子集(子序列)里出现
from typing import List
MOD = int(1e9 + 7)
class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
res = 0
for i, num in enumerate(... |
927d211d656abb69e41ea1fd5f31a68b1af52d52 | 981377660LMT/algorithm-study | /18_哈希/ZobristHashing/multiset哈希.py | 1,476 | 3.59375 | 4 | # multiset哈希
# Zobrist HashingでXOR使うところを、
# !和を使うことで個数にも対応するテクニック、
# 普通に超便利なので将棋AI以外にも浸透したほうが良いと思ってるんだけど、
# 普通に浸透してるのかな。
# https://blog.hamayanhamayan.com/entry/2017/05/24/154618
from collections import Counter, defaultdict
from random import randint
from typing import List, Set
pool = defaultdict(lambda... |
4ae75d25afcd760a77f3f7736b9b443caa267aed | 981377660LMT/algorithm-study | /15_双指针/经典题/交换头部是否可以形成回文串.py | 596 | 3.671875 | 4 | # return whether it is possible to cut both strings at a common point such that the first part of a and the second part of b form a palindrome
# 字符串a与字符串b头部交换,问是否可以形成回文串
# 回文只需要检查i<n//2 的部分
class Solution:
def solve(self, a: str, b: str) -> bool:
def check(s1: str, s2: str) -> bool:
i = ... |
6bbf64c30692c4c74fededcce714920d41920a7c | 981377660LMT/algorithm-study | /7_graph/带权图最短路和最小生成树/dijkstra单源/最短路径树/shortedtPathTree.py | 2,343 | 3.703125 | 4 | # https://www.luogu.com.cn/blog/LawrenceSivan/cf545e-paths-and-trees-zui-duan-lu-jing-shu-post
# 求出最短路径树
# 给定一张带正权的无向图和一个源点,求边权和最小的最短路径树。
# 输出该树权值和和和每条边的编号
from heapq import heappop, heappush
from typing import List, Sequence, Tuple
INF = int(1e18)
def shortestPathTree(
n: int, edges: List[Tuple[i... |
ae7a4d598fe9b013b776e61c1d7bff189ef58a20 | 981377660LMT/algorithm-study | /7_graph/经典题/置换环/UnionEnumetate-动态置换环分组.py | 1,362 | 3.734375 | 4 | # https://noshi91.github.io/Library/data_structure/union_enumerate.cpp
# 比并查集更加轻量的分组
from typing import List
class UnionEnumerate:
__slots__ = ("_next",)
def __init__(self, n: int) -> None:
self._next = list(range(n))
def getAll(self) -> List[List[int]]:
n = len(self._next)... |
27aff46ae9b885b6710cc27be72bdf5e53e9824d | 981377660LMT/algorithm-study | /0_数组/原地操作/字符移位-冒泡排序.py | 664 | 3.890625 | 4 | # 把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
# 注意:字符串不可变的语言是不可能不用额外空间的
# 题目的输入应该改为字符串数组,不用额外空间
from typing import List
def main(arr: List[str]) -> None:
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
# 前面大写后面小写就要交换
if arr[j].isupper() and arr[j + 1... |
84236785fb3c56016e1accbf30e96b71f8c19492 | 981377660LMT/algorithm-study | /22_专题/广义邻居/676. 实现一个魔法字典-广义邻居.py | 1,241 | 3.75 | 4 | from collections import defaultdict
from typing import List
# 将searchWord替换一个字母后,是否存在于dict
# 广义邻居
class MagicDictionary(object):
def __init__(self):
self.adjMap = defaultdict(set) # 广义邻居
def buildDict(self, dictionary: List[str]) -> None:
for word in set(dictionary):
... |
cc26ea544e715a58094cff62912804cf96002176 | 981377660LMT/algorithm-study | /23_设计类/pandas/字符串函数/1667. 修复表中的名字.py | 595 | 3.546875 | 4 | import pandas as pd
data = [[1, "aLice"], [2, "bOB"]]
Users = pd.DataFrame(data, columns=["user_id", "name"]).astype(
{"user_id": "Int64", "name": "object"}
)
# 编写解决方案,修复名字,使得只有第一个字符是大写的,其余都是小写的。
# 返回按 user_id 排序的结果表。
# +---------+-------+
# | user_id | name |
# +---------+-------+
# | 1 | Alice |
# | 2 ... |
d7ab97a0b0acf6e66d0c184d3588f9673c525bfa | 981377660LMT/algorithm-study | /前端笔记/thirtysecondsofcode/python/python的typings/5_联合类型.py | 645 | 4.125 | 4 | from typing import Union
# 联合类型之联合类型会被展平
Union[Union[int, str], float] == Union[int, str, float]
# 在 3.10 版更改: 联合类型现在可以写成 X | Y
# StrOrInt = str | int
# Alternative syntax for unions requires Python 3.10 or newer
# 通常需要使用 isinstance ()检查来首先将联合类型缩小到非联合类型
def f(x: Union[int, str]) -> None:
x + 1 # Error:... |
d91bf1d6e5938dd7464dc6f3a293e4845c96bf97 | 981377660LMT/algorithm-study | /0_数组/摆动数组/978. 最长湍流子序列.py | 318 | 3.59375 | 4 | # 找到最长的子序列使得相邻两项符号交替
class Solution:
def solve(self, nums):
up, down = 0, 0
for num in nums:
if num > 0:
up = max(up, down + 1)
elif num < 0:
down = max(down, up + 1)
return max(up, down)
|
11474db1c2e707e1456e79aa022cf34accc058c5 | 981377660LMT/algorithm-study | /10_分治法/Chessboard Coverage Problem(棋盘覆盖问题).py | 2,649 | 3.90625 | 4 | # 在一个 个方格组成的棋盘中,有一个方格与其它的不同,使用四种L型骨牌覆盖除这个特殊方格的其它方格,请使用分治法实现棋盘覆盖
def chess(startRow: int, startCol: int, specialRow: int, specialCol: int, size: int) -> None:
# tr:棋盘初始行号 tc:棋盘初始列号
# pr:特殊棋盘格行号 pc:特殊棋盘格列号
# size:棋盘格大小
global mark
global table
if size == 1:
return # 递归终止条件
ma... |
71439c279da16d19d155567229b881546cbad8a6 | 981377660LMT/algorithm-study | /22_专题/脑筋急转弯/6172. 严格回文的数字.py | 1,271 | 3.5625 | 4 | # !如果一个整数 n 在 b 进制下(b 为 2 到 n - 2 之间的所有整数)
# !对应的字符串 全部 都是 回文的 ,
# 那么我们称这个数 n 是 严格回文 的。
# 给你一个整数 n ,如果 n 是 严格回文 的,请返回 true ,
# 否则返回 false
class Solution:
def isStrictlyPalindromic(self, n: int) -> bool:
"""
数字 4 在二进制下不是回文的。
对于 n ≥ 5,它们的 (n - 2) 进制表示都是 12,因此也都不是回文的。
直接... |
09abed3d5da54764fb82dfcbfb48675f51caee8c | 981377660LMT/algorithm-study | /11_动态规划/背包问题/完全背包/6011. 完成比赛的最少时间-预处理+dfs.py | 2,157 | 3.75 | 4 | from functools import lru_cache
from typing import List
# 1 <= numLaps <= 1000
# 1 <= tires.length <= 105
# 总结:
# 这道题一开始想贪心的解法(贪心ptsd),sortedList弄了好久,
# 最后才意识到是dp 状态由圈数唯一决定 但是怎么求每个圈的最小时间花费呢?
# 总结:很明显贪心不对的(举反例),就不要贪心了,考虑别的解法,一般是dp,找dfs的自变量是什么,怎么转移,初始值是什么
# 实际上是20个完全背包,凑成numLaps的容量,看最少花费
# 1 <= tires... |
7242e5b04adbead524e5dbd2f22ac2f6bf985d8b | 981377660LMT/algorithm-study | /19_数学/多项式/生成函数/verify/M - Candies-分糖果.py | 650 | 3.546875 | 4 | # n个小朋友 每个小朋友可分0到ai个糖果
# 要分k个糖果 一共有多少种分法 (MOD 1e9+7)
from typing import Tuple
import numpy as np
MOD = int(1e9 + 7)
n, k = map(int, input().split())
A = list(map(int, input().split()))
# 第一个小朋友: (1+x+x^2+...+x^ai) = (1-x^(ai+1))/(1-x)
def gen(i) -> Tuple["np.poly1d", "np.poly1d"]:
arr1 = [0] * (A[i... |
1ae5046573f585ec3899b12983be36c70c5eddce | 981377660LMT/algorithm-study | /6_tree/LCA问题/1740. 找到二叉树中的距离.py | 1,222 | 3.671875 | 4 | from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 返回该二叉树中值为 p 的结点与值为 q 的结点间的 距离 。
class Solution:
def findDistance(self, root: Optional['TreeNode'], p: int, q: int) -> int:
... |
3d598440f0208557fb12c97c5f871f8b2ed70ee6 | 981377660LMT/algorithm-study | /6_tree/LCA问题/1644. 二叉树的最近公共祖先 II.py | 1,605 | 3.640625 | 4 | from typing import Optional
class TreeNode:
def __init__(
self, val: int = 0, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None
):
self.val = val
self.left = left
self.right = right
# 返回给定节点 p 和 q 的最近公共祖先(LCA)节点。
# 如果 p 或 q 之一 不存在 于该二叉树中,返回 nu... |
dbd5a466bef131ddf18a5e72a44c1d13f13c93a1 | 981377660LMT/algorithm-study | /22_专题/字典序列删除/2434. 使用机器人打印字典序最小的字符串.py | 1,535 | 3.640625 | 4 | # 字典序最小的出栈序列
from itertools import accumulate
from collections import Counter
# 给你一个字符串 s 和一个机器人,机器人当前有一个空字符串 t 。
# 执行以下操作之一,直到 s 和 t 都变成空字符串:
# 删除字符串 s 的 第一个 字符,并将该字符给机器人。机器人把这个字符添加到 t 的尾部。
# 删除字符串 t 的 最后一个 字符,并将该字符给机器人。机器人将该字符写到纸上。
class Solution:
def robotWithString(self, s: str) -> str:
... |
9f2a7b550c1c8be1ba3249318f19d7617b72650f | 981377660LMT/algorithm-study | /6_tree/经典题/655. 输出二叉树.py | 1,001 | 3.828125 | 4 | # 输出二叉树
# Definition for a binary tree node.
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[... |
8e42af146965f3f8fd615bfb19f0fa94365e58b8 | 981377660LMT/algorithm-study | /0_数组/原地操作/905. 按奇偶排序数组.py | 757 | 3.8125 | 4 | # 原地首尾指针操作
from typing import List
# nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums) - 1
# left<right的条件始终加上安全一些
while left < right:
# 奇数搬到后面,偶数搬到前面
while left < r... |
bb13136b3ef0a42d50d330c718b435c0d8d58b5e | 981377660LMT/algorithm-study | /7_graph/bfs求无权图的最短路径/多维度bfs/1263. 推箱子.py | 2,657 | 3.5625 | 4 | from collections import deque
from typing import Deque, List, Set, Tuple
# T:目标 B:箱子 S:起点 #:墙
# !返回将箱子推到目标位置的最小 推动 次数,如果无法做到,请返回 -1。
# 1.怎么保证不重复访问:两个位置作为状态
# 2.怎么处理推箱子的位置和不推箱子位置的先后顺序:01bfs
Position = Tuple[int, int]
DIR4 = [[-1, 0], [0, 1], [1, 0], [0, -1]]
class Solution:
def minPushBox(self, ... |
7df8922dbd8b1731972d1dbf55c0f601b2d0e710 | 981377660LMT/algorithm-study | /19_数学/计算几何/凸包与多边形/直线分割凸多边形-convextCut.py | 1,458 | 3.546875 | 4 | # Cutting a convex polygon by a line
from typing import List, Tuple
EPS = 1e-9
Point = Tuple[int, int]
def convex_cut(P: List[Point], line: Tuple[Point, Point]) -> List[Point]:
"""O(N) 求直线分割凸多边形后直线左半部分的凸多边形P,其中多边形的顶点按逆时针方向给出."""
q0, q1 = line
N = len(P)
Q = []
for i in range(N... |
5335afbb13ab2f801511ce9dd62d516a88edc2cc | 981377660LMT/algorithm-study | /11_动态规划/lis最长上升子序列问题/修改为非递减数组的最小操作次数.py | 949 | 4.03125 | 4 | # 蔚来笔试
# 对数组nums的一次操作规定如下:将元素置于第一个位置;将元素置于最后一个位置。
# len(nums)<=3e5
# max(nums)<=1e9
# !求修改为非递减数组的最小操作次数
# 最终肯定是部分数移动过,部分数没移动。
# 只要确定不需要移动的元素的最大数目,就可以得到答案
from typing import List
def minCost(nums: List[int]) -> int:
arr = [(num, i) for i, num in enumerate(nums)]
arr.sort()
print(arr)
... |
562a06c88459432e19d1b3cc66365399509871ad | 981377660LMT/algorithm-study | /6_tree/完全二叉树/父子乘积为偶数的完全二叉树-parent总在前半边.py | 429 | 3.640625 | 4 | # 如果n是奇数 最开始的根要放奇数
# 如果父亲是奇数 儿子必须放偶数
# 如果父亲是偶数 儿子尽量放奇数
# 因为parent总是在数组前半部分 所以数组前半部分全放偶数,后半部分全放奇数
n = int(input())
evens = [i for i in range(1, n + 1) if i % 2 == 0]
odds = [i for i in range(1, n + 1) if i % 2 == 1]
for num in evens + odds:
print(num, end=' ')
|
2b1bc257c8a75272c6cf01b57462c933ab86b922 | 981377660LMT/algorithm-study | /6_tree/KD树/LCP 42. 玩具套圈.py | 629 | 3.703125 | 4 | # 将全部环存在KD-Tree上,然后遍历玩具,找到距离当前玩具最近的点(环),判断一下
from typing import List
from scipy.spatial import KDTree
class Solution:
def circleGame(self, toys: List[List[int]], circles: List[List[int]], r: int) -> int:
kdtree = KDTree(circles)
res = 0
for toy in toys:
nearest: flo... |
7be59bdf7eca1e3b7ba2da67f5a63773cf6616fb | 981377660LMT/algorithm-study | /11_动态规划/经典题/2086. 从房屋收集雨水需要的最少水桶数.py | 1,371 | 3.5625 | 4 | # 你可以在 空位 放置水桶,从相邻的房屋收集雨水。位置在 i - 1 或者 i + 1 的水桶可以收集位置为 i 处房屋的雨水。一个水桶如果相邻两个位置都有房屋,那么它可以收集 两个 房屋的雨水。
# 在确保 每个 房屋旁边都 至少 有一个水桶的前提下,请你返回需要的 最少 水桶数。如果无解请返回 -1 。
# 1 <= street.length <= 105
# If s == 'H', return -1
# If s starts with HH', return -1
# If s ends with HH', return -1
# If s has 'HHH', return -1
# Each... |
ce5f2dca33a6e6fc26db8d4b9de29da3a4d58737 | 981377660LMT/algorithm-study | /11_动态规划/lis最长上升子序列问题/dp变形/删列造序/955. 删列造序 II.py | 1,062 | 3.734375 | 4 | from typing import List
# 选取一个删除索引序列,对于 strs 中的每个字符串,删除对应每个索引处的字符。
# 在执行删除操作之后,最终得到的数组的元素是按 字典序(strs[0] <= strs[1] <= strs[2] ... <= strs[n - 1])排列的,
# 然后请你返回 answer.length 的最小可能值。
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
row = len(strs)
res = 0
curCol... |
6b33cb9047bbe65a272ef46fdc27f194dd920537 | 981377660LMT/algorithm-study | /22_专题/前缀与差分/经典题/2017. 网格游戏.py | 971 | 3.625 | 4 | from typing import List
from itertools import accumulate
# 第一个 机器人想要打击竞争对手,
# 使 第二个 机器人收集到的点数 最小化 。
# 与此相对,第二个 机器人想要 最大化 自己收集到的点数。
# 两个机器人都发挥出自己的 最佳水平 的前提下,返回 第二个 机器人收集到的 点数 。
# 每个机器人只会 向右 ((r, c) 到 (r, c + 1)) 或 向下 ((r, c) 到 (r + 1, c)) 。
# 让第一个机器人取最大值是不对的
class Solution:
def gridGame(self, grid: List... |
709d3d0411dfb064d67c4a6a099aeea10cd530bf | 981377660LMT/algorithm-study | /6_tree/前缀树trie/好题/211. 添加与搜索单词 - 数据结构设计.py | 2,286 | 3.578125 | 4 | from collections import defaultdict
class TrieNode:
__slots__ = ('count', 'preCount', 'children')
def __init__(self):
self.count = 0
self.preCount = 0
self.children = defaultdict(TrieNode)
class Trie:
def __init__(self):
self.root = TrieNode()
def in... |
b7e5ed7844dab0fb83f80a8654113584ea3aa616 | 981377660LMT/algorithm-study | /19_数学/数论/进制/1017. 负二进制转换.py | 1,181 | 3.578125 | 4 | # 给出数字 N,返回由若干 "0" 和 "1"组成的字符串,该字符串为 N 的负二进制(base -2)表示。
# 除非字符串就是 "0",否则返回的字符串中不能含有前导零。
class Solution:
def baseNeg2(self, x: int):
res = []
while x:
div, mod = divmod(x, 2,)
x = -div
res.append(mod)
return "".join(map(str, res[::-1] or [0]))... |
f4cd159b657544484b34b98046f92f8784728490 | 981377660LMT/algorithm-study | /6_tree/分类/构建类/105-从前序和中序还原二叉树-带重复结点.py | 1,048 | 3.65625 | 4 | from typing import List, Optional
class TreeNode:
def __init__(
self, val: int, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None
):
self.val = val
self.left = left
self.right = right
# !带重复结点的前序中序二叉树
class Solution:
def getBinaryTrees(se... |
3766c2bbcc58807b50ee18144eef54534da13c03 | 981377660LMT/algorithm-study | /20_杂题/atc競プロ/AtCoder Beginner Contest/226/A. 四舍五入.py | 546 | 3.515625 | 4 | # 题意:给定一个小数,四舍五入到附近的整数
# !python 四舍五入 py的round函数精度低,尽量避免使用 (python里round和js里round不一样)
# print(round(99.500)) 100
# print(round(42.500)) 42
# print(floor(42.500+0.5)) 43
from math import floor
import sys
sys.setrecursionlimit(int(1e9))
input = lambda: sys.stdin.readline().rstrip("\r\n")
MOD = 998244353
INF... |
19a32f138530b6becca353217fd370bc9febe7bc | 981377660LMT/algorithm-study | /7_graph/二分图/D - RGB Coloring 2-三种颜色给图染色 相邻点颜色不同的方案数.py | 2,021 | 3.625 | 4 | """
三种颜色给图染色的方案数
给定一个无向图 n 个点 m 条边 (n<=20)
现在要给每个点染色 使得相邻的点颜色不同
!在每个连通分量里染色 dfs枚举 时间复杂度O(n^2*2^n)
"""
import sys
from typing import List, Tuple
sys.setrecursionlimit(int(1e9))
input = lambda: sys.stdin.readline().rstrip("\r\n")
def rgbColoring2(n: int, edges: List[Tuple[int, int]]) -> int:
"""三... |
37281e1e27482ad1847549fda1d6f38bcc5b8e5a | 981377660LMT/algorithm-study | /19_数学/模拟退火与爬山法/三分法求凸函数极值.py | 1,725 | 4.15625 | 4 | """
三分法求单峰函数的极值点.
更快的版本见: FibonacciSearch
"""
from typing import Callable
INF = int(4e18)
def minimize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最小值"""
res = INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 ... |
3125e20a2f2d9ed69b8d3c269146c09ea0bed909 | 981377660LMT/algorithm-study | /20_杂题/智力题/时间问题/C-时针分针的夹角与距离.py | 644 | 3.859375 | 4 | # C-时针分针的夹角与距离(不超过180度的夹角)
from math import cos, radians
def calDegree(hour: int, minute: int) -> float:
minuteAngle = minute * 6
hourAngle = hour * 30 + minute * 0.5
return min(abs(minuteAngle - hourAngle), 360 - abs(minuteAngle - hourAngle))
def calDist(hourLength: int, minuteLength: int... |
f0c852f4e484179ecc80bc0c739f6a6b40da27ea | 981377660LMT/algorithm-study | /20_杂题/atc競プロ/AtCoder Beginner Contest/167/B - 银行利息1%.py | 762 | 3.59375 | 4 | # B - 银行利息1%
# 浮点数取整
# !浮点数乘法取整 => 先将浮点数变为整数(*101),再取整(//100)
# 高橋くんはAtCoder銀行に 100 円を預けています。
# AtCoder銀行では、毎年預金額の 1 % の利子がつきます(複利、小数点以下切り捨て)。
# 利子以外の要因で預金額が変化することはないと仮定したとき、高橋くんの預金額が初めて X 円以上になるのは何年後でしょうか。
if __name__ == "__main__":
target = int(input())
money = 100
for i in range(int(1e9)):
... |
5314330f8688d1bbd67c1e9a8544910442cdd900 | 981377660LMT/algorithm-study | /22_专题/离线查询/并查集/1697. 检查边长度限制的路径是否存在-离线边排序.py | 2,404 | 3.515625 | 4 | """
对于每个查询 queries[j] ,判断是否存在从 pj 到 qj 的路径,
且这条路径上的每一条边都 严格小于 limitj 。
按照边权从小到大排序,然后并查集合并
"""
from typing import List
from collections import defaultdict
from typing import DefaultDict, List
class Solution:
def distanceLimitedPathsExist(
self, n: int, edgeList: List[List[int]], queries: ... |
9c355689585701ec6874a81a168709d125d0aebe | 981377660LMT/algorithm-study | /5_map/经典题/反查顺序/1331. 数组序号转换.py | 639 | 3.703125 | 4 | from typing import List
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
nums = sorted(set(arr))
rank_by_value = {}
for index, value in enumerate(nums, 1):
rank_by_value[value] = index
return [rank_by_value[value] for value in arr]
... |
1d71004c74da9628e870bcb2ca88b51208fb462d | 981377660LMT/algorithm-study | /22_专题/区间问题/区间操作/记录preEnd/57. 插入区间.py | 960 | 3.640625 | 4 | from bisect import bisect_left
from typing import List
def merge(intervals: List[List[int]]) -> List[List[int]]:
"""合并所有重叠的有序区间,并返回 一个不重叠的区间数组"""
res = [intervals[0]]
for s, e in intervals[1:]:
if s <= res[-1][1]:
res[-1][1] = max(res[-1][1], e)
else:
res... |
484cef67470018a572249f990178184b02e91cf1 | 981377660LMT/algorithm-study | /tmp/20211129/1029. 两地调度.py | 637 | 3.640625 | 4 | from typing import List
# 返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达。
# 我们将每位顾客按照飞往A的金额-飞往B的金额差值来进行排序。
# 排在前面的肯定应该飞往A,而排在后面的人就理所应当的要飞往B了
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
costs.sort(key=lambda pair: pair[0] - pair[1])
return sum(v[0] if i < len(c... |
7636530f8ce1f567b19122fc3c8360f064545447 | 981377660LMT/algorithm-study | /5_map/邻接表/1348. 推文计数.py | 1,587 | 3.796875 | 4 | from typing import List
from collections import defaultdict
from sortedcontainers import SortedList
class TweetCounts:
"""一家社交媒体公司正试图通过分析特定时间段内出现的推文数量来监控其网站上的活动。"""
def __init__(self):
self.tweets = defaultdict(SortedList)
def recordTweet(self, tweetName: str, time: int) -> None:
... |
64d7e38ae7d52c4cd48d9cca46e01df0dd26433e | 981377660LMT/algorithm-study | /前端笔记/thirtysecondsofcode/python/python的typings/9_类型守卫.py | 502 | 3.796875 | 4 | from typing import List
from typing_extensions import TypeGuard
def is_str_list(val: List[object]) -> TypeGuard[List[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: List[object]):
if is_str_list(val):
# Typ... |
de4239838d8407bceb1d40382703e74d96638d24 | 981377660LMT/algorithm-study | /tmp/20230327/6355. 质数减法运算.py | 2,059 | 3.53125 | 4 | # 给你一个下标从 0 开始的整数数组 nums ,数组长度为 n 。
# 你可以执行无限次下述运算:
# 选择一个之前未选过的下标 i ,并选择一个 严格小于 nums[i] 的质数 p ,从 nums[i] 中减去 p 。
# !如果你能通过上述运算使得 nums 成为严格递增数组,则返回 true ;否则返回 false 。
# 严格递增数组 中的每个元素都严格大于其前面的元素。
from bisect import bisect_left
from collections import Counter
from typing import List
class EratosthenesSiev... |
382859ab8a570247585fc7ea6d7f539ac48d1fcc | 981377660LMT/algorithm-study | /9_排序和搜索/分类/插入排序二分/493. 翻转对.py | 671 | 3.6875 | 4 | # 如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。输出对数
# 思路:倒序遍历 nums(保证i<j),遍历过的数我们将它 乘 2,放入 tb 中,同时保持 tb 是按升序排列的。
import bisect
from typing import List
def reversePairs(nums: List[int]) -> int:
res = 0
double = []
for i in reversed(nums):
# 每次遍历开始比较i与2j的关系,二分法看看是第几位
r... |
1d15f0b809679559a7d1881d577f09a6ad82ffce | 981377660LMT/algorithm-study | /7_graph/拓扑排序/Transitive Reduction of DAG-DAG的传递简约.py | 2,153 | 3.671875 | 4 | #
# Transitive Reduction of DAG
#
# Description:
# A transitive reduction of a graph G = (V, E) is a
# a graph H = (V, F) such that transitive closures of
# H and G are the same.
# There are possibly many transitive reductions with
# the fewest edges, and finding one of them is NP-hard.
# On he other h... |
8d28d6f0969abf50cc7d447a9e411a46aca44200 | 981377660LMT/algorithm-study | /20_杂题/智力题/时间问题/949. 给定数字能组成的最大时间.py | 570 | 3.5 | 4 | from typing import List
from itertools import permutations
class Solution:
def largestTimeFromDigits(self, arr: List[int]) -> str:
return max(
("{}{}:{}{}".format(*p) for p in permutations(arr) if p[:2] < (2, 4) and p[2] < 6),
default='',
)
print(Solution().la... |
13d20b304aae12002336d52e9586f108f6528b9b | 981377660LMT/algorithm-study | /7_graph/带权图最短路和最小生成树/kruskal/模板.py | 2,648 | 3.65625 | 4 | from collections import defaultdict
from typing import DefaultDict, List, Tuple
def kruskal(n: int, edges: List[Tuple[int, int, int]]) -> Tuple[int, List[int]]:
"""Kruskal算法求无向图最小生成树
Args:
n (int): 节点`个数`,并查集初始化为(0,1,2,...,n-1)
edges (List[Tuple[int, int, int]]): 边的列表,每个元素是`(u, v, w)... |
739de844cc7a1bce13cfe47ee3600369c62bb36c | 981377660LMT/algorithm-study | /22_专题/区间问题/两个区间的交集.py | 359 | 3.609375 | 4 | from typing import Optional, Tuple
def getIntersect(
interval1: Tuple[int, int], interval2: Tuple[int, int]
) -> Optional[Tuple[int, int]]:
"""获取两个区间的交集"""
if interval1[0] > interval2[1] or interval2[0] > interval1[1]:
return None
return (max(interval1[0], interval2[0]), min(interval1... |
c4ffede202634c2d23bc22676a88b001572b12f1 | 981377660LMT/algorithm-study | /7_graph/bfs求无权图的最短路径/1992. 找到所有的农场组.py | 1,230 | 3.5 | 4 | from typing import List
from collections import deque
# 题目要求:求出每个连通区域(保证是矩形)的左上角/右下角坐标
# 用bfs即可,起始点是左上角,不断更新右下角,最后一个点肯定是右下角
class Solution:
def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
m, n = len(land), len(land[0])
res = []
for i in range(m):
for ... |
0d9fa9a2e977babc33005ffe51eeab630811cfd9 | 981377660LMT/algorithm-study | /20_杂题/骑士距离.py | 910 | 3.921875 | 4 | # 骑士距离
# 棋盘上马从(0,0)到目标点的最短路径
def knight_distance(tx: int, ty: int) -> int:
"""https://maspypy.github.io/library/other/knight_distance.hpp"""
max = lambda x, y: x if x > y else y
tx = abs(tx)
ty = abs(ty)
if tx + ty == 0:
return 0
if tx + ty == 1:
return 3
if tx... |
5c5e9433612554aaf19f4f413dfb1e1cdacdd862 | 981377660LMT/algorithm-study | /11_动态规划/经典题/dfs+cache/字典序路径后序dfs/943. 最短超级串-dfs返回路径.py | 1,652 | 3.546875 | 4 | from functools import lru_cache
from typing import List
# 大部分状态压缩dp,Python都可以用cache和frozenset来实现
# 1 <= words.length <= 12
# 1 <= words[i].length <= 20
# words[i] 由小写英文字母组成
# words 中的所有字符串 互不相同
@lru_cache(None)
def calWeight(u: str, v: str) -> int:
return next(k for k in range(len(v), -1, -1) if u.en... |
a2279a0605e1188c60f01bfa353f3962b5f7b5d6 | 981377660LMT/algorithm-study | /11_动态规划/lis最长上升子序列问题/在不改变顺序的情况下将数组分成递增和递减子序列.py | 1,348 | 3.609375 | 4 | # 百度之星
# !在不改变顺序的情况下将数组分成递增子序列和递减子序列
# n<=1e5
# https://www.imangodoc.com/192611.html
# 对于新元素x,
# - 如果它只能附加到数组之一,则附加它。
# - 如果它不能附加到任何一个,那么答案是-1。
# - 如果它可以附加到两个元素,则检查下一个元素y,
# - 如果 y > x 则将x附加到增加的元素,否则将x附加到减少的元素。
from itertools import groupby
from typing import List, Tuple
INF = int(4e18)
def splitAr... |
8fa1c15b8bb8f645a06b217d89913b86d8e1c385 | 981377660LMT/algorithm-study | /7_graph/二分图/带权二分图的最大权匹配问题/6232. 最小移动总距离.py | 1,099 | 3.796875 | 4 | from typing import List
from KM算法模板 import KM
INF = int(1e18)
class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
"""带权图最大权匹配
Args:
robot (List[int]): 机器人的位置
factory (List[List[int]]): 每个工厂的(位置,可以修理的机器人个数)
... |
dedca28e26ad7792759edf98feaabb9795f1e60b | 981377660LMT/algorithm-study | /tmp/20211215/2018. 判断单词是否能放入填字游戏内.py | 1,196 | 3.578125 | 4 | from typing import List
from itertools import chain
# 1 <= m * n <= 2 * 105 (暗示遍历m*n)
# 如果单词是 水平 放置的,那么该单词左边和右边 相邻 格子不能为 ' ' 或小写英文字母。
# 如果单词是 竖直 放置的,那么该单词上边和下边 相邻 格子不能为 ' ' 或小写英文字母。
# 看到还是没什么思路
# 每一行和每一列的字符串按 '#' 分割为子串,判断每个子串是否匹配 word 或 word[::-1] 即可。
class Solution:
def placeWordInCrossword(self, boa... |
7f78ee553a8d6200de8df9f25b1e115eb21b7546 | 981377660LMT/algorithm-study | /11_动态规划/dp分类/树上dp/后序dfs/337. 打家劫舍 III.py | 628 | 3.578125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rob(self, root: 'TreeNode') -> int:
def dfs(root: 'TreeNode'):
if not root:
... |
40eb99a4210a5bd4265dafdcb22d9a8e48d11d09 | 981377660LMT/algorithm-study | /19_数学/计算几何/凸包与多边形/凸多边形的交点.py | 4,629 | 3.671875 | 4 | from typing import List, Tuple
Point = Tuple[int, int]
# ps, qs: a polygon (counter-clockwise)
def is_convex_polygons_intersection(ps: List[Point], qs: List[Point]) -> bool:
"""两个凸多边形是否相交,其中多边形的顶点按逆时针方向给出."""
pl = len(ps)
ql = len(qs)
i = j = 0
while (i < pl or j < ql) and (i < 2 * pl)... |
610f51dce398776d8271552f5a070779f5bb367e | 981377660LMT/algorithm-study | /7_graph/带权图最短路和最小生成树/dijkstra单源/k短路.py | 3,031 | 3.8125 | 4 | # k短路(K-Shortest Walk)
# n,m,k<=3e5
# 给定有向图
# 输出从s到t的k条最短路长度
from heapq import heappop, heappush
from typing import List, Tuple
INF = int(1e18)
def main():
n, m, start, end, k = map(int, input().split())
adjList = [[] for _ in range(n)]
for _ in range(m):
u, v, w = map(int, input(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.