优秀代码样板收集计划(python)

  • 快速输出
  • dfs,thread,python3,defaultdict,换根dp
  • Counter,元组map
  • 捕获异常
  • 数组排序翻转切片
  • bfs
  • accumulate
  • 二维数组读入,math库调用
  • 字符串
  • counter数组
  • bisect(lower_bound upper_bound)
  • 列表推导式

输出

sys.stdout.write(" ".join(map(str,ans))+"\n")

dfs,bootstrap ,换根DP

import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict

BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(2 * 10 ** 5)





ans=0

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc


@bootstrap
def dfs(now, lay, fa):
    SUM[now] = 0
    NUM[now] = C[now]
    for to in A[now]:
        if to != fa:
            yield dfs(to, lay + 1, now)
            SUM[now] += SUM[to]
            SUM[now] += NUM[to]
            NUM[now] += NUM[to]
    yield


@bootstrap
def change(now, fa):
    global ans
    ans = max(ans, SUM[now])
    for to in A[now]:
        if to != fa:
            SUM[now] -= SUM[to]
            SUM[now] -= NUM[to]
            NUM[now] -= NUM[to]
            NUM[to] += NUM[now]
            SUM[to] += SUM[now]
            SUM[to] += NUM[now]

            yield change(to, now)

            SUM[to] -= SUM[now]
            SUM[to] -= NUM[now]
            NUM[to] -= NUM[now]
            NUM[now] += NUM[to]
            SUM[now] += SUM[to]
            SUM[now] += NUM[to]
    yield


n = int(input())
A = [[] for i in range(n + 1)]
C = [0] + (list(map(int, input().split())))
NUM = [0] * (n + 1)
SUM = [0] * (n + 1)
for i in range(n - 1):
    x, y = map(int, input().split())
    A[x].append(y)
    A[y].append(x)
dfs(1, 0, 0)
change(1, 0)
print(ans)
# print(NUM)
# print(SUM)

dfs,thread,python3,defaultdict,换根dp

from collections import defaultdict
import threading
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
for CASES in range(int(input())):
'''
inf = 100000000000000000  # 1e17
mod = 998244353

A = defaultdict(list)
son = defaultdict(int)
dp = defaultdict(int)

n = int(input())
for CASES in range(n - 1):
    x, y = map(int, input().split())
    A[x].append(y)
    A[y].append(x)


def dfs1(now, fa):  # get son
    son[now] = 1
    for to in A[now]:
        if to == fa:
            continue
        dfs1(to, now)
        son[now] += son[to]


def dfs2(now, fa):  # get dp
    dp[now] = son[now]
    for to in A[now]:
        if to == fa:
            continue
        dfs2(to, now)
        dp[now] += dp[to]


def dfs3(now, fa):  # transfer
    global ans
    ans = max(ans, dp[now])
    for to in A[now]:
        if to == fa:
            continue
        dp[now] -= dp[to] + son[to]
        dp[to] += dp[now] + (n - son[to])
        dfs3(to, now)
        dp[to] -= dp[now] + (n - son[to])
        dp[now] += dp[to] + son[to]


def main():
    dfs1(1, 0)
    dfs2(1, 0)
    dfs3(1, 0)


ans = 0
t = threading.Thread(target=main)
t.start()
t.join()
print(ans)

counter

from collections import Counter
import sys
input = sys.stdin.readline
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
for CASES in range(int(input())):
'''
inf = 100000
mod = 998244353


def fac(x):
    i = 2
    while i * i <= x:
        if x % i == 0:
            cnt = 0
            while x % i == 0:
                cnt += 1
                x //= i
            cnt %= k
            if cnt > 0:
                sig.append((i, cnt))
        i += 1
    if x > 1:
        sig.append((x, 1))


n, k = map(int, input().split())
A = list(map(int, input().split()))

ans = 0
prev = Counter()
for a in A:
    sig = []
    fac(a)
    com_sig = []
    for p, val in sig:
        com_sig.append((p, k - val))
    ans += prev[tuple(sig)]
    prev[tuple(com_sig)] += 1
print(ans)

try

    try:
        n = int(v)
    except Exception as e:
        print("Couldn't parse")
        print('Reason:', e)

数组排序切片

import sys
input = sys.stdin.readline
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
for test in range(int(input())):
'''
inf = 100000000000000000  # 1e17

x, y, a, b, c = map(int, input().split())
array_a = list(map(int, input().split()))
array_b = list(map(int, input().split()))
array_c = list(map(int, input().split()))
array_a = sorted(array_a, reverse=True)[:x]
array_b = sorted(array_b, reverse=True)[:y]
ans = sum(sorted(array_a + array_b + array_c, reverse=True)[:x + y])
print(ans)

bfs

from itertools import accumulate
from collections import deque
def bfs(STA):
    DIS = [-1] * (n + 1)
    Q = deque([STA])
    DIS[STA] = 0
    while Q:
        x = Q.pop()
        for to in A[x]:
            if DIS[to] == -1:
                DIS[to] = DIS[x] + 1
                Q.appendleft(to)
    return DIS

accumulate

input = sys.stdin.readline
from itertools import accumulate
 
t=int(input())
for tests in range(t):
    n,k=map(int,input().split())
    A=list(map(int,input().split()))
    ANS=[0]*(k*2+3)
 
    for i in range(n//2):
        x,y=A[i],A[n-1-i]
        if x>y:
            x,y=y,x
 
        #print(x,y)
 
        ANS[x+1]-=1
        ANS[y+k+1]+=1
        ANS[x+y]-=1
        ANS[x+y+1]+=1
 
        #print(ANS)
 
    #print(ANS)
 
    S=list(accumulate(ANS))
    #print(S)
 
    print(n+min(S))

二维数组读入,math库调用

# https://codeforces.com/contest/1220/problem/B
import sys
input=sys.stdin.readline

n=int(input())
A=[list(map(int,input().split())) for i in range(n)]

from math import ceil,sqrt
ANS=[]
tmp=A[0][1]*A[0][2]//A[1][2]
ANS.append(ceil(sqrt(tmp)))
for i in range(1,n):
    ANS.append(A[0][i]//ANS[0])
print(*ANS)

字符串

import sys
input=sys.stdin.readline

n=input()
S=input().strip()

one=S.count("n")
zero=S.count("z")
ANS=[1]*one+[0]*zero
print(*ANS)

Counter数组

https://codeforces.com/contest/1208/problem/B
import sys
input=sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))

from collections import Counter
import copy
C=Counter(A)
for a in A:
    if C[a]<=1:
        del C[a]
if not(C):
    print(0)
    sys.exit()

ans=n-1
for i in range(n):
    D=copy.deepcopy(C)
    for j in range(i,n):
        if D[A[j]]>1:
            D[A[j]]-=1
        if D[A[j]]==1:
            del D[A[j]]
        if not(D):
            ans=min(ans,j-i+1)
            break
print(ans)

bisect

import bisect

L = [1,3,3,3,6,8,12,15]
x = 3

x_insert_point = bisect.bisect_left(L,x)
print (x_insert_point)

x_insert_point = bisect.bisect_right(L,x)
print(x_insert_point)

列表推导式

# https://codeforces.com/contest/1332/problem/C
def f(l):
    d={}
    for i in l:
        if i in d:
            d[i]+=1
        else:
            d[i]=1
    return len(l)-max(d.values())

import sys
for _ in range(int(sys.stdin.readline())):
    n,k=map(int,sys.stdin.readline().split())
    s=input()
    print(sum(f(s[j::k]+s[k-j-1::k]) for j in range(k//2))+sum(f(s[k//2::k]) for j in range(k%2)))

进制转换

def toshi(x):
    if '0'<=x<='9':
        return ord(x)-48
    return ord(x)-ord('a')+10
def shito(x):
    if 0<=x<=9:
        return chr(x+48)
    return chr(x-10+ord('a'))
s=input()
a,b=map(int,input().split())
ans=0
for i in s:
    ans*=a
    ans+=toshi(i)
if ans==0:
    print(0)
pr=''
while ans>0:
    pr=shito(ans%b)+pr
    ans//=b
print(pr)

初始化数组并设两边为无穷大

A[0]=float("inf")
A[n+1]=float("inf")

交互问题输出

print("?",mid,flush=True)
posted on 2020-05-02 14:25  xlinsist  阅读(212)  评论(0编辑  收藏  举报