from collections import Counter
from bisect import bisect_right

N,K=map(int,input().split())
A=[int(input()) for _ in range(N)]

A = [A[i]-K for i in range(N)]

cum=[0]
for i in range(N):
  cum.append(cum[-1]+A[i])

c = Counter(cum[1:])
items = sorted(c.items(),reverse=True)

data=[(10**20,0)]
for k,num in items:
  data.append((k,data[-1][1]+num))

data = dict(data[::-1])

ans = 0
past=[]
for i in range(N):
  cu = cum[i+1]
  if data.get(cu):
    ans += data[cu]
    data[cu] -= 1
  if i == 0:
    past.append(cu)
    continue
  idx = bisect_right(past,cu)
  ans -= len(past)-idx
  past.insert(idx,cu)

print(ans)


n, m = map(int,input().split())
road = [list(map(int,input().split())) for _ in range(m)]
cnt = [0] * n
for i in road:
    cnt[i[0]-1] += 1
    cnt[i[1]-1] += 1
for j in range(n):
    print(cnt[j])

#n = int(input())
n, m = map(int, input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
dic = {i: 0 for i in range(1, n+1)}
for i in range(m):
    a, b = map(int, input().split())
    dic[a] = dic[a]+1
    dic[b] = dic[b]+1

for i in range(1, n+1):
    print(dic[i])

Score : <var>200</var> points

Problem Statement

There are <var>N</var> cities and <var>M</var> roads.
The <var>i</var>-th road <var>(1≤i≤M)</var> connects two cities <var>a_i</var> and <var>b_i</var> <var>(1≤a_i,b_i≤N)</var> bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

<var>2≤N,M≤50</var>

<var>1≤a_i,b_i≤N</var>

<var>a_i ≠ b_i</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_M</var> <var>b_M</var>

Output

Print the answer in <var>N</var> lines.
In the <var>i</var>-th line <var>(1≤i≤N)</var>, print the number of roads connected to city <var>i</var>.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City <var>1</var> is connected to the <var>1</var>-st and <var>3</var>-rd roads.

City <var>2</var> is connected to the <var>1</var>-st and <var>2</var>-nd roads.

City <var>3</var> is connected to the <var>2</var>-nd road.

City <var>4</var> is connected to the <var>3</var>-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

8 8
1 2
3 4
1 5
2 8
3 7
5 2
4 1
6 8

Sample Output 3

3
3
2
2
2
1
1
2


import itertools
from collections import Counter
from typing import List

def answer(n: int, m: int, ab_s: List[List[int]]) -> List[int]:
    counter = Counter(itertools.chain.from_iterable(ab_s))
    roads = list(i[1] for i in sorted(counter.items()))
    return roads

def main():
    n, m = map(int, input().split())
    ab_s = [list(map(int, input().split())) for _ in range(m)]
    for i in answer(n, m, ab_s):
        print(i)

if __name__ == '__main__':
    main()


numbers = list(map(lambda x: int(x), input().split()))
nums = list(map(lambda x: int(x), input().split()))
t = numbers[1]

total = t
for i in range(1, len(nums)):
    check = nums[i] - nums[i - 1]
    total += check if check <= t else t

print(total)

# -*- coding: utf-8 -*-
"""
Created on Sun Sep 27 03:05:21 2020

@author: liang
"""

N ,T = map(int,input().split())

time = [int(x) for x in input().split()]

ans = 0
for i in range(N-1):
    ans += min(T, time[i+1]-time[i])
ans += T
print(ans)

Score : <var>300</var> points

Problem Statement

In a public bath, there is a shower which emits water for <var>T</var> seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for <var>T</var> seconds.
Note that it does not mean that the shower emits water for <var>T</var> additional seconds.

<var>N</var> people will push the switch while passing by the shower.
The <var>i</var>-th person will push the switch <var>t_i</var> seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

<var>1 ≤ N ≤ 200,000</var>

<var>1 ≤ T ≤ 10^9</var>

<var>0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9</var>

<var>T</var> and each <var>t_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>T</var>
<var>t_1</var> <var>t_2</var> ... <var>t_N</var>

Output

Assume that the shower will emit water for a total of <var>X</var> seconds. Print <var>X</var>.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


import math
from math import gcd,pi,sqrt
INF = float("inf")

import sys
sys.setrecursionlimit(10**6)
import itertools
from collections import Counter,deque
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]

def main():
    N,T = i_map()

    t = i_list()

    ans = 0
    for i,k in enumerate(t[1:], start=1):
        if k <= T:
            ans += k - t[i-1]
        else:
            ans += T
    ans += T
    print(ans)

if __name__=="__main__":
    main()


import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
    N, W, *WV = map(int, read().split())
    weight = WV[::2]
    value = WV[1::2]

    w_min = min(weight)
    items = [[] for _ in range(4)]
    for w, v in zip(weight, value):
        items[w - w_min].append(v)

    for i in range(4):
        items[i].sort(reverse=True)

    csums = [0] * 4
    for i in range(4):
        csums[i] = [0]
        csums[i].extend(accumulate(items[i]))

    def rec(i, w, v):
        if i == 4:
            if w <= W:
                return v
            else:
                return -1
        ans = 0
        for j in range(len(csums[i])):
            w_next = w + (w_min + i) * j
            if w_next > W:
                break
            ans = max(ans, rec(i + 1, w_next, v + csums[i][j]))

        return ans

    print(rec(0, 0, 0))
    return

if __name__ == '__main__':
    main()

import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
    N, W, *WV = map(int, read().split())
    weight = WV[::2]
    value = WV[1::2]

    w_min = min(weight)
    items = [[] for _ in range(4)]
    for w, v in zip(weight, value):
        items[w - w_min].append(v)

    for i in range(4):
        items[i].sort(reverse=True)

    csums = [0] * 4
    for i in range(4):
        csums[i] = [0]
        csums[i].extend(accumulate(items[i]))

    def rec(i, w, v):
        if i == 4:
            if w <= W:
                return v
            else:
                return -1
        ans = 0
        for j in range(len(csums[i])):
            ans = max(ans, rec(i + 1, w + (w_min + i) * j, v + csums[i][j]))

        return ans

    print(rec(0, 0, 0))
    return

if __name__ == '__main__':
    main()

Score : <var>400</var> points

Problem Statement

You have <var>N</var> items and a bag of strength <var>W</var>.
The <var>i</var>-th item has a weight of <var>w_i</var> and a value of <var>v_i</var>.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most <var>W</var>.

Your objective is to maximize the total value of the selected items.

Constraints

<var>1 ≤ N ≤ 100</var>

<var>1 ≤ W ≤ 10^9</var>

<var>1 ≤ w_i ≤ 10^9</var>

For each <var>i = 2,3,...,N</var>, <var>w_1 ≤ w_i ≤ w_1 + 3</var>.

<var>1 ≤ v_i ≤ 10^7</var>

<var>W</var>, each <var>w_i</var> and <var>v_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>W</var>
<var>w_1</var> <var>v_1</var>
<var>w_2</var> <var>v_2</var>
:
<var>w_N</var> <var>v_N</var>

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


n,w=map(int, input().split())

weight=[]
value=[]
for _ in range(n):
    _w,_v=map(int, input().split())
    weight.append(_w)
    value.append(_v)

def knapsack(n, w, weight, value):
    # 初期化
    _dp = [[-float("inf") for _ in range(w+1)] for _ in range(n+1)]
    for _i in range(w+1):
        _dp[0][_i] = 0

    # DP
    for _i in range(n):
        for _j in range(w+1):
            # dp[i][w-weight[i]] の状態にi番目の荷物が入る可能性がある
            if weight[_i] <= _j:
                _dp[_i+1][_j] = max(_dp[_i][w-weight[_i]]+value[_i], _dp[_i][_j])
            else:  # 入る可能性はない
                _dp[_i+1][_j] = _dp[_i][_j]
    # print(_dp)
    return _dp[n][w]

print(knapsack(n,w,weight,value))


N, W = map(int, input().split())

WVs = [list(map(int, input().split())) for _ in range(N)]

memo = {}
def dp(i, capacity):
    if i == N:
        return 0
    if (i, capacity) in memo:
        return memo[(i, capacity)]
    ret = dp(i+1, capacity)
    w, v = WVs[i]
    if w <= capacity:
        ret2 = dp(i+1, capacity - w) + v
        ret = ret if ret > ret2 else ret2
    memo[(i, capacity)] = ret
    return ret

print(dp(0, W))

#!/usr/bin python3
# -*- coding: utf-8 -*-

n, w = map(int, input().split())
vi = [[] for _ in range(4)]
wi0, vi0 = map(int, input().split())
vi[0].append(vi0)

for _ in range(n-1):
    wii, vii = map(int, input().split())
    vi[wii-wi0].append(vii)

for i in range(4):
    vi[i].sort(reverse=True)
    vi[i] = [0] + vi[i]
    for j in range(1, len(vi[i])):
        vi[i][j] += vi[i][j-1]

ret = 0
for i in range(len(vi[3])):
    for j in range(len(vi[2])):
        for k in range(len(vi[1])):
            tw = i*(wi0+3)+j*(wi0+2)+k*(wi0+1)
            l = max(0,min(len(vi[0])-1,(w - tw)//wi0))
            tw += l*(wi0)
            if tw > w: continue
            tv = vi[3][i]+vi[2][j]+vi[1][k]+vi[0][l]
            ret = max(ret, tv)
print(ret)


from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,W = inpl()
a = [inpl() for _ in range(n)]
gds = [[0] for _ in range(4)]
a.sort()
mi = a[0][0]
for i,(w,v) in enumerate(a):
    ind = w - mi
    gds[ind].append(v)
we = [i+mi for i in range(4)]
cnt = [0] * 4
for i in range(4):
    gds[i].sort()
    cnt[i] = len(gds[i])
    tmp = itertools.accumulate(gds[i])
    gds[i] = list(tmp)
it = itertools.product(range(cnt[0]),range(cnt[1]),range(cnt[2]),range(cnt[3]))
res = 0
for ww in it:
    w0,w1,w2,w3 = ww
    if sum(we[i]*ww[i] for i in range(4)) > W: continue
    now = gds[0][w0] + gds[1][w1] + gds[2][w2] + gds[3][w3]
    res = max(now, res)
print(res)


def abc059a(s1: str, s2: str, s3: str) ->str:
    return s1[0].upper() + s2[0].upper() + s3[0].upper()

s1, s2, s3 = map(str, input().split())
print(abc059a(s1, s2, s3))

#n = int(input())
a, b, c = map(str, input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]

a = a.upper()
b = b.upper()
c = c.upper()
print(a[0]+b[0]+c[0])

Score : <var>100</var> points

Problem Statement

You are given three words <var>s_1</var>, <var>s_2</var> and <var>s_3</var>, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

<var>s_1</var>, <var>s_2</var> and <var>s_3</var> are composed of lowercase English letters.

<var>1 ≤ |s_i| ≤ 10 (1≤i≤3)</var>

Input

Input is given from Standard Input in the following format:

<var>s_1</var> <var>s_2</var> <var>s_3</var>

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


def atc_059a(input_value: str) -> str:
    S = input_value.split(" ")
    SSS = S[0][0].upper() + S[1][0].upper() + S[2][0].upper()
    return SSS


#n = int(input())
#a, b = map(int,input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
a = str(input())
b = str(input())
if len(a) < len(b):
    ans = 'LESS'
elif len(a) > len(b):
    ans = 'GREATER'
else:
    n = len(a)
    ans = 'EQUAL'
    for i in range(n):
        if a[i] < b[i]:
            ans = 'LESS'
            break
        elif a[i] > b[i]:
            ans = 'GREATER'
            break
print(ans)

a=int(input())
b=int(input())

if a==b:print("EQUAL")
elif a>b:print("GREATER")
else:print("LESS")

Score : <var>200</var> points

Problem Statement

You are given two positive integers <var>A</var> and <var>B</var>. Compare the magnitudes of these numbers.

Constraints

<var>1 ≤ A, B ≤ 10^{100}</var>

Neither <var>A</var> nor <var>B</var> begins with a 0.

Input

Input is given from Standard Input in the following format:

<var>A</var>
<var>B</var>

Output

Print GREATER if <var>A>B</var>, LESS if <var>A<B</var> and EQUAL if <var>A=B</var>.

Sample Input 1

36
24

Sample Output 1

GREATER

Since <var>36>24</var>, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


a = int(input())
b = int(input())
if a < b:
  print("LESS")
elif a > b:
  print("GREATER")
else:
  print("EQUAl")


from bisect import*
n,*s,t=open(0)
x,y=[sorted(u.replace('?',c)for u in s)for c in'za']
print(*range(bisect_left(x,t)+1,bisect(y,t)+2))

# ?を全てaに変えたときと、zに変えたときの順位を求める
import sys
readline = sys.stdin.readline

N = int(readline())

Alist = [None] * N
Zlist = [None] * N
for i in range(N):
  line = readline().rstrip()
  Alist[i] = line.replace("?","a")
  Zlist[i] = line.replace("?","z")

Alist = sorted(Alist)
Zlist = sorted(Zlist)

T = readline().rstrip()

import bisect
end = bisect.bisect_right(Alist, T)
start = bisect.bisect_left(Zlist, T)

print(*list(range(start + 1, end + 2)))

				Max Score: <var>250</var> Points

Problem Statement

					Mr.X, who the handle name is <var>T</var>, looked at the list which written <var>N</var> handle names, <var>S_1, S_2, ..., S_N</var>.

					But he couldn't see some parts of the list. Invisible part is denoted ?.

					Please calculate all possible index of the handle name of Mr.X when you sort <var>N+1</var> handle names (<var>S_1, S_2, ..., S_N</var> and <var>T</var>) in lexicographical order.

					Note: If there are pair of people with same handle name, either one may come first.

Input

						The input is given from standard input in the following format.

<var>N</var>
<var>S_1</var>
<var>S_2</var>
 :
<var>S_N</var>
<var>T</var>

Output

Calculate the possible index and print in sorted order. The output should be separated with a space. Don't print a space after last number.

Put a line break in the end.

Constraints

<var>1 ≤ N ≤ 10000</var>

<var>1 ≤ |S_i|, |T| ≤ 20</var> (<var>|A|</var> is the length of <var>A</var>.)

<var>S_i</var> consists from lower-case alphabet and ?.

<var>T</var> consists from lower-case alphabet.

Scoring

Subtask 1 [ <var>130</var> points ]

There are no ?'s.

Subtask 2 [ <var>120</var> points ]

There are no additional constraints.

Sample Input 1

2
tourist
petr
e

Sample Output 1

1

					There are no invisible part, so there are only one possibility.
					The sorted handle names are e, petr, tourist, so e comes first.

Sample Input 2

2
?o?r?s?
?et?
e


import bisect
N = int(input())
S = [input() for _ in range(N)]
T = input()
best = []
worse = []
for s in S:
    best.append(s.replace('?', 'z'))
    worse.append(s.replace('?', 'a'))
ans=[]
for i in range(bisect.bisect_left(best,T)+1,bisect.bisect_right(worse,T)+2):
    ans.append(i)
print(*ans)


def resolve():
    def dfs1(topo, par):
        for idx in reversed(topo):
            ret = 0
            child = 0
            for to in G[idx]:
                if to == par[idx]:
                    continue
                ret += EV[to] + 1.0
                child += 1
            #EV[idx] = 0
            if child >= 1:
                EV[idx] += ret / child

    def dfs2(idx, d_par, par):
        stack = [(idx, d_par, par)]
        while stack:
            idx, d_par, par = stack.pop()
            ret = 0
            for to in G[idx]:
                if to == par:
                    ret += d_par + 1.0
                else:
                    ret += EV[to] + 1.0
            ans[idx] = ret / len(G[idx])
            for to in G[idx]:
                if to == par:
                    continue
                max_l = max(1, len(G[idx]) - 1)
                nx_d_par = (ret - EV[to] - 1.0) / max_l
                stack.append((to, nx_d_par, idx))

    N = int(input())
    G = [[] for _ in range(N)]
    for i in range(N - 1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append(b)
        G[b].append(a)

    topo = []
    P = [-1] * N
    node = [0]
    while node:
        v = node.pop()
        topo.append(v)
        for to in G[v]:
            if to == P[v]:
                continue
            P[to] = v
            node.append(to)

    EV = [0] * N
    ans = [0] * N
    dfs1(topo, P)
    dfs2(0, 0, -1)
    for i in range(N):
        print(ans[i])

if __name__ == "__main__":
    resolve()

import sys
sys.setrecursionlimit(10 ** 7)

def resolve():
    def dfs1(idx, par):
        ret = 0
        child = 0
        for to in G[idx]:
            if to == par:
                continue
            dfs1(to, idx)
            ret += EV[to] + 1.0
            child += 1
        EV[idx] = 0
        if child >= 1:
            EV[idx] += ret / child

    def dfs2(idx, d_par, par):
        ret = 0
        for to in G[idx]:
            if to == par:
                ret += d_par + 1.0
            else:
                ret += EV[to] + 1.0
        ans[idx] = ret / len(G[idx])
        for to in G[idx]:
            if to == par:
                continue
            max_l = max(1, len(G[idx]) - 1)
            nx_d_par = (ret - EV[to] - 1.0) / max_l
            dfs2(to, nx_d_par, idx)

    N = int(input())
    G = [[] for _ in range(N)]
    for i in range(N - 1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append(b)
        G[b].append(a)

    EV = [0] * N
    ans = [0] * N
    dfs1(0, -1)
    dfs2(0, 0, -1)
    for i in range(N):
        print(ans[i])

if __name__ == '__main__':
    resolve()

				Max Score: $800$ Points

Problem Statement

					There is an undirected connected graph with $N$ vertices and $N-1$ edges. The <var>i</var>-th edge connects <var>u_i</var> and <var>v_i</var>.

					E869120 the coder moves in the graph as follows:

He move to adjacent vertex, but he can't a visit vertex two or more times.

He ends move when there is no way to move.

Otherwise, he moves randomly. (equal probability) If he has $p$ way to move this turn, he choose each vertex with $1/p$ probability.

					Calculate the expected value of the number of turns, when E869120 starts from vertex <var>i</var>, for all <var>i (1 ≤ i ≤ N)</var>.

Input

						The input is given from standard input in the following format.

<var>N</var>
<var>u_1</var> <var>v_1</var>
<var>u_2</var> <var>v_2</var>
 :
<var>u_{N-1}</var> <var>v_{N-1}</var>

Output

						In <var>i</var>-th <var>(1 ≤ i ≤ N)</var> line, print the expected vaule of the number of turns E869120 moves.

						The relative error or absolute error of output should be within <var>10^{-6}</var>.

Constraints

$1 \le N \le 150,000$

The graph is connected.

Subtasks

Subtask 1 [ $190$ points ]

There is no vertex which degree is more than 2.

This means the graph looks like a list.

Subtask 2 [ $220$ points ]

<var>1 ≤ N ≤ 1000</var>.

Subtask 3 [ $390$ points ]

There are no additional constraints.

Sample Input 1

4
1 2
2 3
2 4

Sample Output 1

2.0
1.0
2.0
2.0

Sample Input 2

4
1 2
2 4
4 3


#recursion-version

#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_A&lang=jp
#http://penguinshunya.hatenablog.com/entry/2019/07/09/003006

import sys
sys.setrecursionlimit(1000000)

inpPh = 1
debug = True
#debug = False
if not debug:
    inpPh = 0

input1 ='''
12
1 2
2 3
2 4
4 5
5 6
5 7
6 8
8 9
2 10
10 11
11 12
'''[1:]

input2 ='''
7
1 2
1 3
2 4
2 5
3 6
3 7
'''[1:]

input1bk ='''
4
1 2
2 3
2 4
'''[1:]

#input1 = input2

output1_2='''
5 7
'''

inputXs = [input1, input2,None]

if debug:
    try:
        inputXs.append(inputA0)
    except:
        pass
    else:
        pass

inploc = inpPh - 1 #0,1,2

if inpPh > 0:
    #print('selected_input:\n'+inputXs[inploc])
    #print('')
    pass

inpX_lst = []
if debug and inpPh > 0:
    inpX_lst = inputXs[inploc].splitlines()

if inpPh ==0:
    n = int(input())
else:
    n = int(inpX_lst.pop(0) )

st_list = []
noe_vwise = [0 for _ in range(n)]

for i in range(n-1):
    if inpPh ==0:
        si,ti = tuple(map(lambda x: int(x), input().split() ) )
    else:
        si,ti = tuple(map(lambda x: int(x), inpX_lst.pop(0).split() ) )

    noe_vwise[si-1] += 1
    #noe_vwise[ti-1] += 1
    st_list.append((si-1,ti-1))

#print(st_list)

from collections import namedtuple
INF = float('inf')

Edge = namedtuple('Edge', ['to', 'value'])
def Edge(x,y):
    return (x,y)

def reroot(n, es_vwise, dp_es_vwise, e_init, noe_vwise, pe_vwise):

    def dfs1(v,v_par):
        nonlocal es_vwise, dp_es_vwise, e_init, vpar_v
        stack = [(v,v_par)]
        while stack:
            (v,v_par) = stack.pop()

        #print('es_vwise[v]',v,es_vwise[v])
        ret = e
        #ret = Edge(-INF,-INF)
        ret = (0, 0)

        for i in range(len(es_vwise[v]) ):
            e_local = es_vwise[v][i]
            if (e_local[0] == v_par):
                print('this-part should not be printed')
                vpar_v[v] = i
                continue

            dp_es_vwise[v][i] = lift(dfs1(e_local[0], v), e_local[1]  )
            #dp_es_vwise[v][i] = lift(dfs1(e_local[0], v), e_local[1] )
            ret = merge(ret, dp_es_vwise[v][i] )
        return ret

    def dfs2(v, t):
        # bundlable_parental_edge = t
        nonlocal ans, es_vwise, dp_es_vwise, vpar_v, e_init
        nonlocal pe_vwise

        if (vpar_v[v] is not None):
            pass
            #lift(parental_edge, gparental_edge)
            #dp_es_vwise[v][vpar_v[v]] = lift(t,es_vwise[v][vpar_v[v]][1] )

        l = len(es_vwise[v])
        dpl = [e_init for i in range(l+1) ]
        dpr = [e_init for i in range(l+1) ]

        if (pe_vwise[v] is not None):
            v0, v1, w = pe_vwise[v]
            dpr[l] = lift(t,w)

        for i in range(l):
            dpl[i+1] = merge(dpl[i], dp_es_vwise[v][i])
        for i in range(l-1,-1,-1):
            dpr[i] = merge(dpr[i+1], dp_es_vwise[v][i])
            #l: 0->1, l-1->l
            #r: l->l-1, 1->0

        ans[v] = dpr[0]

        for i in range(l):
            if (i == vpar_v[v]):
                print('continue, l',0)
                continue
            u = es_vwise[v][i][0]

            dfs2(u, merge(dpl[i], dpr[i+1]) )

    def lift(a,w):
        if a[1] == 0:
            return (w,1)

        return ( (a[0] / a[1]) + w, 1)

    def merge(a,b):
        # print("merge:",a,b)
        return (a[0] + b[0], a[1]+b[1])

    nov = n
    vpar_v = [None for i in range(nov)]
    vpar_v0 = [None for i in range(nov)]

    for i in range(len(es_vwise)):
        for e in es_vwise[i]:
            vpar_v0[e[0]] = i

    ans = [Edge(0,-INF) for i in range(nov)]
    dfs1(0,None)
    #0 must be root?
    dfs2(0,None)
    ret = 0

    for i in range(len(ans)):
        #print(f'i:{i} ans:{ans[i]}')
        print(float(ans[i][0] / ans[i][1]))

    return ans

class reroot_init:
    def __init__(self,n,noe_vwise):
        self.n = n
        self.es_vwise = [ [] for i in range(n)]
        self.dp_es_vwise = [ [] for i in range(n)]
        self.pe_vwise = [ None for i in range(n)]
        parental_edge_vwise = self.pe_vwise

    def movemain(self):
        reroot(n,self.es_vwise, self.dp_es_vwise, (-INF,-INF), noe_vwise, {})

def main():
    rri = reroot_init(n, noe_vwise)
    es_vwise = [ [] for i in range(n)]
    dp_es_vwise = [ [] for i in range(n)]
    pe_vwise = [ None for i in range(n)]

    edges_vwise = es_vwise ; parental_edge_vwise = pe_vwise

    def v_add_edge(v,u,w):
        es_vwise[v].append((u,w))
        dp_es_vwise[v].append((0, -INF))

    for st in st_list:
        s,t = st
        #print(stw)
        v_add_edge(s,t,1)
        pe_vwise[t] = (s,t,1)

    e_init = (0,0)

    reroot(n, es_vwise, dp_es_vwise, e_init, noe_vwise, pe_vwise)

main()


a = input()
b = input()
s = ""
for i in range(len(b)):
    s += a[i] + b[i]
if len(a) > len(b):
    s += a[-1]
print(s)

#n = int(input())
#a, b = map(int,input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
o = list(input())
e = list(input())
oc = 0
ec = 0

ans = ''

n = len(o)+len(e)
for i in range(1,n+1):
    if i % 2 == 0:
        add = e[ec]
        ec += 1
    else:
        add = o[oc]
        oc += 1
    ans += add

print(ans)

Score : <var>200</var> points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings <var>O</var> and <var>E</var>. <var>O</var> contains the characters at the odd-numbered positions retaining their relative order, and <var>E</var> contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

<var>O</var> and <var>E</var> consists of lowercase English letters (a - z).

<var>1 \leq |O|,|E| \leq 50</var>

<var>|O| - |E|</var> is either <var>0</var> or <var>1</var>.

Input

Input is given from Standard Input in the following format:

<var>O</var>
<var>E</var>

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


o = input()
e = input()

res = ""
for i, j in zip(o, e):
    res += i + j
print(res)


import sys

input = sys.stdin.buffer.readline
in_n = lambda: int(input())
in_nn = lambda: map(int, input().split())
in_s = lambda: input().rstrip().decode('utf-8')
in_map = lambda: [s == ord('.') for s in input() if s != ord('\n')]

MOD = 10**9 + 7
INF = 8 * 10**18

def main():

    N, M = in_nn()
    X = list(in_nn())
    Y = list(in_nn())

    x_tsum = [0] * (N + 1)
    for i in range(N):
        x_tsum[i + 1] += x_tsum[i] + X[i]
        x_tsum[i + 1] %= MOD

    x_sum = 0
    for i in range(1, N):
        x_sum += X[i] * i - x_tsum[i]
        x_sum %= MOD

    y_tsum = [0] * (M + 1)
    for i in range(M):
        y_tsum[i + 1] += y_tsum[i] + Y[i]
        y_tsum[i + 1] %= MOD

    y_sum = 0
    for i in range(1, M):
        y_sum += Y[i] * i - y_tsum[i]
        y_sum %= MOD

    print(x_sum * y_sum % MOD)

if __name__ == '__main__':
    main()

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#mod = 998244353
#from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

n, m = MAP()
x = LIST()
y = LIST()

def acc(A):
	acc = []
	tmp = 0
	for a in A:
		tmp += a
		tmp %= mod
		acc.append(tmp)
	return acc

def sum_combinations(A, k):
	A_acc = acc(A)
	A_sum = 0

	for i in range(k):
		tmp = (A_acc[-1] - A_acc[i]) %mod
		tmp = (tmp-A[i] * (k-1-i)%mod) %mod
		A_sum = (A_sum + tmp) %mod

	return A_sum

print(sum_combinations(x, n) * sum_combinations(y, m) %mod)

Score : <var>500</var> points

Problem Statement

On a two-dimensional plane, there are <var>m</var> lines drawn parallel to the <var>x</var> axis, and <var>n</var> lines drawn parallel to the <var>y</var> axis.
Among the lines parallel to the <var>x</var> axis, the <var>i</var>-th from the bottom is represented by <var>y = y_i</var>.
Similarly, among the lines parallel to the <var>y</var> axis, the <var>i</var>-th from the left is represented by <var>x = x_i</var>.

For every rectangle that is formed by these lines, find its area, and print the total area modulo <var>10^9+7</var>.

That is, for every quadruple <var>(i,j,k,l)</var> satisfying <var>1\leq i < j\leq n</var> and <var>1\leq k < l\leq m</var>, find the area of the rectangle formed by the lines <var>x=x_i</var>, <var>x=x_j</var>, <var>y=y_k</var> and <var>y=y_l</var>, and print the sum of these areas modulo <var>10^9+7</var>.

Constraints

<var>2 \leq n,m \leq 10^5</var>

<var>-10^9 \leq x_1 < ... < x_n \leq 10^9</var>

<var>-10^9 \leq y_1 < ... < y_m \leq 10^9</var>

<var>x_i</var> and <var>y_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>n</var> <var>m</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_n</var>
<var>y_1</var> <var>y_2</var> <var>...</var> <var>y_m</var>

Output

Print the total area of the rectangles, modulo <var>10^9+7</var>.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is <var>60</var>.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


n,m=map(int,input().split())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
mod=(10**9) + 7

X = abs(x[n-1]-x[0])%mod
Y = abs(y[m-1]-y[0])%mod
K = pow(2,n+m-4,mod)

print((X*Y*K)%mod)


from collections import deque
import sys
sys.setrecursionlimit(10**6)
n,m = map(int,input().split())
e = [[] for i in range(n+1)]
for i in range(m):
    a,b = map(int,input().split())
    e[a].append(b)
    e[b].append(a)
qv = int(input())
Q = [list(map(int,input().split())) for i in range(qv)]

color = [0]*(n+1)
used = [-1]*(n+1)

for v,d,c in Q[::-1]:
    if used[v] > d:
        continue

    q = deque([[v,d]])
    while q:
        now, dis = q.popleft()
        if dis < 0:
            continue
        if color[now] == 0:
            color[now] = c
        for nex in e[now]:
            if used[nex] < dis-1:
                used[nex] = dis-1
                q.append([nex,dis-1])

for i in color[1:]:
    print(i)

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

n, m = map(int, input().split())
path = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    path[a - 1].append(b - 1)
    path[b - 1].append(a - 1)
q = int(input())
query = []
for i in range(q):
    v, d, c = map(int, input().split())
    query.append((i+1, v - 1, d, c))
dp = [[0] * 11 for i in range(n)]
def paint(v, d, i, dp, path):
    if dp[v][d] == 0:
        dp[v][d] = i
        if d > 0:
            paint(v, d - 1, i, dp, path)
            for u in path[v]:
                paint(u, d - 1, i, dp, path)
    return

for i, v, d, c in query[::-1]:
    paint(v, d, i, dp, path)
for i in range(n):
    if dp[i][0] == 0:
        print(0)
    else:
        print(query[dp[i][0]-1][3])

Score : <var>700</var> points

Problem Statement

Squid loves painting vertices in graphs.

There is a simple undirected graph consisting of <var>N</var> vertices numbered <var>1</var> through <var>N</var>, and <var>M</var> edges.
Initially, all the vertices are painted in color <var>0</var>. The <var>i</var>-th edge bidirectionally connects two vertices <var>a_i</var> and <var>b_i</var>. The length of every edge is <var>1</var>.

Squid performed <var>Q</var> operations on this graph. In the <var>i</var>-th operation, he repaints all the vertices within a distance of <var>d_i</var> from vertex <var>v_i</var>, in color <var>c_i</var>.

Find the color of each vertex after the <var>Q</var> operations.

Constraints

<var>1 ≤ N,M,Q ≤ 10^5</var>

<var>1 ≤ a_i,b_i,v_i ≤ N</var>

<var>a_i ≠ b_i</var>

<var>0 ≤ d_i ≤ 10</var>

<var>1 ≤ c_i ≤10^5</var>

<var>d_i</var> and <var>c_i</var> are all integers.

There are no self-loops or multiple edges in the given graph.

Partial Score

<var>200</var> points will be awarded for passing the testset satisfying <var>1 ≤ N,M,Q ≤ 2{,}000</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_{M}</var> <var>b_{M}</var>
<var>Q</var>
<var>v_1</var> <var>d_1</var> <var>c_1</var>
<var>:</var>
<var>v_{Q}</var> <var>d_{Q}</var> <var>c_{Q}</var>

Output

Print the answer in <var>N</var> lines.
In the <var>i</var>-th line, print the color of vertex <var>i</var> after the <var>Q</var> operations.

Sample Input 1

7 7
1 2
1 3
1 4
4 5
5 6
5 7
2 3
2
6 1 1
1 2 2

Sample Output 1

2
2
2
2
2
1
0

Initially, each vertex is painted in color <var>0</var>.
In the first operation, vertices <var>5</var> and <var>6</var> are repainted in color <var>1</var>.
In the second operation, vertices <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var> and <var>5</var> are repainted in color <var>2</var>.

Sample Input 2

14 10
1 4
5 7
7 11
4 10
14 7
14 3
6 14
8 11
5 13
8 3
8
8 6 2
9 7 85
6 9 3
6 7 5
10 3 1
12 9 4
9 6 6
8 2 3

Sample Output 2

1
0
3
1
5
5
3
3
6
1
3
4
5
3

The given graph may not be connected.


from collections import deque

n, m = map(int, input().split())
G = [list() for _ in range(n)]
for _ in range(m):
  a, b = map(int, input().split())
  a -= 1; b -= 1
  G[a].append(b)
  G[b].append(a)
Q = int(input())
queries = [tuple(map(int, input().split())) for _ in range(Q)][::-1]
dp = [[Q]*11 for _ in range(n)]
for i, (v, d, _) in enumerate(queries):
  dp[v-1][d] = i
for d in range(10, 0, -1):
  for v in range(n):
    if dp[v][d] < Q:
      dp[v][d-1] = min(dp[v][d-1], dp[v][d])
      for x in G[v]:
        dp[x][d-1] = min(dp[x][d-1], dp[v][d])
queries.append((-1, -1, 0))
color = [queries[dp[v][0]][2] for v in range(n)]
print(*color, sep='\n')


n,m=map(int,input().split())
l_n=[list(map(int,input().split())) for _ in range(n)]
l_m=[list(map(int,input().split())) for _ in range(m)]
# print(l_n,l_m)

for i,j in l_n:
    distance=0
    cnt = 0
    ans = float ( "inf" )
    for k,l in enumerate(l_m):
        a,b=l
        distance=abs(i-a)+abs(j-b)
        if ans>distance:
            ans=min(ans,distance)
            cnt=k+1
    print(cnt)

n,m=map(int,input().split())
l_n=[list(map(int,input().split())) for _ in range(n)]
l_m=[list(map(int,input().split())) for _ in range(m)]
# print(l_n,l_m)

for i,j in l_n:
    distance=0
    cnt = 0
    ans = float ( "inf" )
    for k,l in enumerate(l_m,1):
        a,b=l
        distance=abs(i-a)+abs(j-b)
        if ans>distance:
            ans=min(ans,distance)
            cnt=k
    print(cnt)

Score : <var>200</var> points

Problem Statement

There are <var>N</var> students and <var>M</var> checkpoints on the <var>xy</var>-plane.

The coordinates of the <var>i</var>-th student <var>(1 \leq i \leq N)</var> is <var>(a_i,b_i)</var>, and the coordinates of the checkpoint numbered <var>j</var> <var>(1 \leq j \leq M)</var> is <var>(c_j,d_j)</var>.

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points <var>(x_1,y_1)</var> and <var>(x_2,y_2)</var> is <var>|x_1-x_2|+|y_1-y_2|</var>.

Here, <var>|x|</var> denotes the absolute value of <var>x</var>.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

<var>1 \leq N,M \leq 50</var>

<var>-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8</var>

All input values are integers.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_N</var> <var>b_N</var>
<var>c_1</var> <var>d_1</var>
<var>:</var>
<var>c_M</var> <var>d_M</var>

Output

Print <var>N</var> lines.

The <var>i</var>-th line <var>(1 \leq i \leq N)</var> should contain the index of the checkpoint for the <var>i</var>-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint <var>1</var>: <var>|2-(-1)|+|0-0|=3</var>

For checkpoint <var>2</var>: <var>|2-1|+|0-0|=1</var>

The nearest checkpoint is checkpoint <var>2</var>. Thus, the first line in the output should contain <var>2</var>.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint <var>1</var>: <var>|0-(-1)|+|0-0|=1</var>

For checkpoint <var>2</var>: <var>|0-1|+|0-0|=1</var>

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain <var>1</var>.

Sample Input 2

3 4
10 10
-10 -10
3 3
1 2
2 3
3 5
3 5

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


n,m=map(int,input().split())
l_n=[list(map(int,input().split())) for _ in range(n)]
l_m=[list(map(int,input().split())) for _ in range(m)]

for i,j in l_n:
    distance=0
    cnt = 0
    ans = float ( "inf" )
    for k,l in enumerate(l_m):
        a,b=l
        distance=(i-a)**2+(j-b)**2
        if ans>distance:
            ans=min(ans,distance)
            cnt=k+1
    print(cnt)


from itertools import accumulate

N, *A = map(int, open(0).read().split())
A.sort()
acc = list(accumulate(A))
ans = N
for i in range(N - 1):
    if 3 * acc[i] < acc[i + 1]:
        ans = N - i - 1
print(ans)

import numpy as np
n = int(input())
al = sorted(list(map(int, input().split())))
c = list(np.cumsum(al))

ans = 1
for i in range(n-1):
    if c[i]*2 >= al[i+1]:
        ans += 1
    else:
        ans = 1

print(ans)

Score : <var>400</var> points

Problem Statement

Snuke found <var>N</var> strange creatures.
Each creature has a fixed color and size. The color and size of the <var>i</var>-th creature are represented by <var>i</var> and <var>A_i</var>, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size <var>A</var> and color <var>B</var> absorbs another creature of size <var>C</var> and color <var>D</var> (<var>C \leq 2 \times A</var>), they will merge into one creature of size <var>A+C</var> and color <var>B</var>.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

<var>2 \leq N \leq 100000</var>

<var>1 \leq A_i \leq 10^9</var>

<var>A_i</var> is an integer.

Input

The input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> … <var>A_N</var>

Output

Print the number of the possible colors of the last remaining creature after the <var>N</var> creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors <var>1</var> and <var>3</var>.
For example, when the creature of color <var>3</var> absorbs the creature of color <var>2</var>, then the creature of color <var>1</var> absorbs the creature of color <var>3</var>, the color of the last remaining creature will be color <var>1</var>.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


N = int(input())
A = list(map(int, input().split()))

A = sorted(A)

wa = A[0]  # i - 1 までの和
cnt = 1  # i 番目の生き物より小さかったのに、i 番目の生き物を食べれるやつの数
for i in range(1, N):
    if 2 * wa >= A[i]:
        cnt += 1
    else:
        cnt = 1
    wa += A[i]
    print(cnt)


import sys

def check_bipartite(s, links, visited):
    q = [(s, 0)]
    is_bipartite = True
    count = 0
    while q:
        v, color = q.pop()
        if visited[v] != -1:
            if visited[v] != color:
                is_bipartite = False
            continue
        visited[v] = color
        count += 1
        new_color = color ^ 1
        for u in links[v]:
            if visited[u] != -1:
                if visited[u] != new_color:
                    is_bipartite = False
                continue
            q.append((u, new_color))
    return is_bipartite, count

n, m = map(int, sys.stdin.buffer.readline().split())
links = [set() for _ in range(n)]
mp = map(int, sys.stdin.buffer.read().split())
for u, v in zip(mp, mp):
    u -= 1
    v -= 1
    links[u].add(v)
    links[v].add(u)

visited = [-1] * n
count_bipartite = 0
count_non_bipartite = 0
count_isolated = 0
ans = 0
for v in range(n):
    if visited[v] != -1:
        continue
    is_bipartite, count = check_bipartite(v, links, visited)
    if count == 1:
        count_isolated += 1
    elif is_bipartite:
        count_bipartite += 1
    else:
        count_non_bipartite += 1

ans = count_isolated * (n * 2 - count_isolated)
ans += count_non_bipartite * (count_non_bipartite + count_bipartite * 2)
ans += count_bipartite ** 2 * 2

print(ans)

import sys
input =  sys.stdin.readline

n, m = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(m):
  u, v = map(int, input().split())
  u -= 1
  v -= 1
  G[u].append(v)
  G[v].append(u)
seen = [-1]*n
p, q, r = 0, 0, 0
def dfs(v):
  stack = [(v, 0)]
  seen[v] = 0
  f = False
  while stack:
    v, c = stack.pop()
    for nv in G[v]:
      if seen[nv] == -1:
        seen[nv] = c^1
        stack.append((nv, c^1))
      else:
        if seen[nv]^c == 0:
          f = True
  return f
for v in range(n):
  if seen[v] != -1:
    continue
  if not G[v]:
    r += 1
  else:
    if dfs(v):
      p += 1
    else:
      q += 1
ans = r*(2*n-r) + (p+q)*(p+q) + q*q
print(ans)

Score : <var>800</var> points

Problem Statement

Takahashi has received an undirected graph with <var>N</var> vertices, numbered <var>1</var>, <var>2</var>, ..., <var>N</var>.
The edges in this graph are represented by <var>(u_i, v_i)</var>.
There are no self-loops and multiple edges in this graph.

Based on this graph, Takahashi is now constructing a new graph with <var>N^2</var> vertices, where each vertex is labeled with a pair of integers <var>(a, b)</var> (<var>1 \leq a \leq N</var>, <var>1 \leq b \leq N</var>).
The edges in this new graph are generated by the following rule:

Span an edge between vertices <var>(a, b)</var> and <var>(a', b')</var> if and only if both of the following two edges exist in the original graph: an edge between vertices <var>a</var> and <var>a'</var>, and an edge between vertices <var>b</var> and <var>b'</var>.

How many connected components are there in this new graph?

Constraints

<var>2 \leq N \leq 100,000</var>

<var>0 \leq M \leq 200,000</var>

<var>1 \leq u_i < v_i \leq N</var>

There exists no pair of distinct integers <var>i</var> and <var>j</var> such that <var>u_i = u_j</var> and <var>v_i = v_j</var>.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>u_1</var> <var>v_1</var>
<var>u_2</var> <var>v_2</var>
:
<var>u_M</var> <var>v_M</var>

Output

Print the number of the connected components in the graph constructed by Takahashi.

Sample Input 1

3 1
1 2

Sample Output 1

7

The graph constructed by Takahashi is as follows.

Sample Input 2

7 5
1 2
3 4
3 5
4 5
2 6

Sample Output 2

18


import sys
def input():
	return sys.stdin.readline()[:-1]

n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
	u, v = map(int, input().split())
	adj[u-1].append(v-1)
	adj[v-1].append(u-1)

visited = [False for _ in range(n)]
tree, loop = 0, 0

def dfs(start):
	global tree, loop
	is_tree = True
	stack = [(start, -1)]
	while stack:
		x, p = stack.pop()
		for v in adj[x]:
			if v == p:
				continue
			elif visited[v]:
				is_tree = False
			else:
				visited[v] = True
				stack.append((v, x))
	if is_tree:
		tree += 1
	else:
		loop += 1
	return

for i in range(n):
	if not visited[i] and adj[i]:
		visited[i] = True
		dfs(i)

alone = n - sum(visited)
ans = 2*tree + loop + 2*tree*(tree-1) + 2*tree*loop + loop*(loop-1)//2
ans += alone*(2*n-alone)

print(ans)


import sys
from itertools import accumulate
from collections import deque

def solve():
    N, K = map(int, input().split())
    S = input()

    '''
    if N == 1:
        if K % 2 == 0:
            print(S)
        else:
            print('A' if S == 'B' else 'B')

        return
    '''

    q = deque([1 if c == 'A' else 0 for c in S])
    cb = 0

    for i in range(min(K, 2 * N + K % 2)):
        if q[0] == (cb ^ 1):
            q[0] ^= 1
        else:
            q.popleft()
            q.append(cb)
            cb ^= 1

    # print(q)

    ans = ['A' if (c ^ cb) else 'B' for c in q]
    print(''.join(ans))

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

if __name__ == '__main__':
    solve()

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from collections import deque

# f(AX) = XB
# f(BX) = flip(X) + A = flip(XB)

N,K = map(int,readline().split())
S = read().rstrip()
S = deque(0 if x == b'A'[0] else 1 for x in S)

# Kが大きいときは、周期で減らせる
U = 10**6
if K > U:
    K = U + (K&1)

flip = 0
for _ in range(K):
    top = S[0]^flip
    if top == 0:
        # A
        S[0] ^= 1
    else:
        # B
        flip ^= 1
        S.popleft()
        S.append(flip)

if flip == 0:
    A = 'A'; B = 'B'
else:
    A = 'B'; B = 'A'
answer = ''.join(A if x == 0 else B for x in S)
print(answer)

Score : <var>900</var> points

Problem Statement

Takahashi has a lot of peculiar devices.
These cylindrical devices receive balls from left and right.
Each device is in one of the two states A and B, and for each state, the device operates as follows:

When a device in state A receives a ball from either side (left or right), the device throws out the ball from the same side, then immediately goes into state B.

When a device in state B receives a ball from either side, the device throws out the ball from the other side, then immediately goes into state A.

The transition of the state of a device happens momentarily and always completes before it receives another ball.

Takahashi built a contraption by concatenating <var>N</var> of these devices. In this contraption,

A ball that was thrown out from the right side of the <var>i</var>-th device from the left (<var>1 \leq i \leq N-1</var>) immediately enters the <var>(i+1)</var>-th device from the left side.

A ball that was thrown out from the left side of the <var>i</var>-th device from the left (<var>2 \leq i \leq N</var>) immediately enters the <var>(i-1)</var>-th device from the right side.

The initial state of the <var>i</var>-th device from the left is represented by the <var>i</var>-th character in a string <var>S</var>.
From this situation, Takahashi performed the following <var>K</var> times: put a ball into the leftmost device from the left side, then wait until the ball comes out of the contraption from either end.
Here, it can be proved that the ball always comes out of the contraption after a finite time.
Find the state of each device after <var>K</var> balls are processed.

Constraints

<var>1 \leq N \leq 200,000</var>

<var>1 \leq K \leq 10^9</var>

<var>|S|=N</var>

Each character in <var>S</var> is either A or B.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>S</var>

Output

Print a string that represents the state of each device after <var>K</var> balls are processed.
The string must be <var>N</var> characters long, and the <var>i</var>-th character must correspond to the state of the <var>i</var>-th device from the left.

Sample Input 1

5 1
ABAAA

Sample Output 1

BBAAA

In this input, we put a ball into the leftmost device from the left side, then it is returned from the same place.

Sample Input 2

5 2
ABAAA

Sample Output 2

ABBBA

Sample Input 3

4 123456789
AABB

Sample Output 3

BABA


def solution():
	n,k = [int(x) for x in input().split(' ')]
	txt = input()
	s = list(txt)
	cycle = []
	nbr = 0
	cache = {}
	suffix = ''
	while (txt+suffix) not in cycle:
		cycle.append(txt+suffix)
		position = 0
		toLeft = True
		suffix = ''
		while txt[len(txt)-len(suffix)-2:] == 'BA':
			suffix+='BA'
			txt = txt[(len(txt)-len(suffix)-2):]
		s = list(txt)
		while position<len(s) and position>=0:

			if s[position] == 'A':
				s[position] = 'B'
				toLeft = not(toLeft)
			else:
				s[position] = 'A'

			position +=1 if toLeft else -1

		nbr +=1
		txt = ''.join(s)
		if nbr == k:
			return txt

	startingCycle = cycle.index(txt+suffix)
	cycle = cycle[startingCycle:]
	return cycle[(k-startingCycle)%len(cycle)]

print(solution())


from collections import Counter
n = int(input())
a = list(map(int, input().split()))
c = Counter(a)
d = list(c.values())
if (n % 2 == 1 and c[0] == 1 and d.count(2) == (n-1)//2) or (n % 2 == 0 and d.count(2) == n//2):
    print(pow(2, n//2, 10**9+7))
else:
    print(0)

n = int(input())
A = sorted(map(int,input().split()))

if n % 2 == 1:
    ex = [0]

    for i in range(n//2):
        a = 2 * (i+1)
        ex += [a,a]

else:
    ex = []
    a = 1

    for i in range(n//2):
        ex += [a,a]
        a += 2

ans = 0

if A == ex:
    ans = 2 ** (n//2) % (10**9 + 7)

print(ans)

Score : <var>300</var> points

Problem Statement

There are <var>N</var> people, conveniently numbered <var>1</var> through <var>N</var>.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person <var>i</var> is <var>A_i</var>.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo <var>10^9+7</var>.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print <var>0</var>.

Constraints

<var>1≦N≦10^5</var>

<var>0≦A_i≦N-1</var>

Input

The input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the number of the possible orders in which they were standing, modulo <var>10^9+7</var>.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

<var>2,1,4,5,3</var>

<var>2,5,4,1,3</var>

<var>3,1,4,5,2</var>

<var>3,5,4,1,2</var>

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is <var>0</var>.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


N=int(input())
MOD=1000000007
A=list(map(int,input().split()))
cnt=[0 for i in range(N)]
for i in range(N):
    cnt[A[i]]+=1
if N%2==0:
    for i in range(1,N,2):
        if cnt[i]!=2:
            print(0)
            break
    else:
        print(2**(N//2)%MOD)
else:
    if cnt[0]!=1:
        print(0)
    else:
        for i in range(2,(N+1)//2,2):
            if cnt[i]!=2:
                print(0)
                break
        else:
            print(2**((N-1)//2))


import sys
from networkx.utils import UnionFind
def input(): return sys.stdin.readline().rstrip()

def main():
    n,m=map(int, input().split())
    lang=[[] for i in range(m+1)]
    for i in range(1,n+1):
        for talk in list(map(int, input().split()))[1:]:
            lang[talk].append(i)
    uf = UnionFind()
    for langs in lang:
        if len(langs) >=1:
            uf.union(*langs)
    print('YES' if len(list(uf.to_sets()))==1 else 'NO')

if __name__ == '__main__':
    main()

from collections import deque
n,m=map(int,input().split())
edge=[[] for _ in range(n+m)]
for i in range(n):
    lis=list(map(int,input().split()))
    for l in lis[1:]:
        l-=1
        edge[i].append(n+l)
        edge[n+l].append(i)
def bfs():
    visited=[0]*(n+m)
    q=deque([0])
    visited[0]=1
    while q:
        x=q.popleft()
        for nx in edge[x]:
            if visited[nx]==0:
                visited[nx]=1
                q.append(nx)
    return visited
visited=bfs()
if sum(visited[:n])==n:
    print("YES")
else:
    print("NO")

Score : <var>400</var> points

Problem Statement

On a planet far, far away, <var>M</var> languages are spoken. They are conveniently numbered <var>1</var> through <var>M</var>.

For CODE FESTIVAL 20XX held on this planet, <var>N</var> participants gathered from all over the planet.

The <var>i</var>-th <var>(1≦i≦N)</var> participant can speak <var>K_i</var> languages numbered <var>L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}</var>.

Two participants <var>A</var> and <var>B</var> can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both <var>A</var> and <var>B</var> can speak.

There exists a participant <var>X</var> that both <var>A</var> and <var>B</var> can communicate with.

Determine whether all <var>N</var> participants can communicate with all other participants.

Constraints

<var>2≦N≦10^5</var>

<var>1≦M≦10^5</var>

<var>1≦K_i≦M</var>

<var>(</var>The sum of all <var>K_i)≦10^5</var>

<var>1≦L_{i,j}≦M</var>

<var>L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}</var> are pairwise distinct.

Partial Score

<var>200</var> points will be awarded for passing the test set satisfying the following: <var>N≦1000</var>, <var>M≦1000</var> and <var>(</var>The sum of all <var>K_i)≦1000</var>.

Additional <var>200</var> points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>K_1</var> <var>L_{1,1}</var> <var>L_{1,2}</var> <var>...</var> <var>L_{1,{}K_1}</var>
<var>K_2</var> <var>L_{2,1}</var> <var>L_{2,2}</var> <var>...</var> <var>L_{2,{}K_2}</var>
<var>:</var>
<var>K_N</var> <var>L_{N,1}</var> <var>L_{N,2}</var> <var>...</var> <var>L_{N,{}K_N}</var>

Output

If all <var>N</var> participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

4 6
3 1 2 3
2 4 2
2 4 6
1 6

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants <var>1</var> and <var>2</var>: both can speak language <var>2</var>.

Participants <var>2</var> and <var>3</var>: both can speak language <var>4</var>.

Participants <var>1</var> and <var>3</var>: both can communicate with participant <var>2</var>.

Participants <var>3</var> and <var>4</var>: both can speak language <var>6</var>.

Participants <var>2</var> and <var>4</var>: both can communicate with participant <var>3</var>.

Participants <var>1</var> and <var>4</var>: both can communicate with participant <var>2</var>.

Note that there can be languages spoken by no participant.

Sample Input 2

4 4
2 1 2
2 1 2
1 3
2 4 3

Sample Output 2

NO

For example, participants <var>1</var> and <var>3</var> cannot communicate with each other.


def unite(x,y):
	rx=root(x)
	ry=root(y)
	if rank[rx]<rank[ry]:
		parent[rx]=ry
	else:
		parent[ry]=rx
		if rank[rx]==rank[ry]:
			rank[rx]+=1
def same(x,y):
	return root(x)==root(y)
def root(x):
	if x!=parent[x]:
		x=root(parent[x])
	return x
n,m=map(int,input().split())
parent=list(range(n+m))
rank=[0]*(n+m)
for i in range(n):
	l=list(map(int,input().split()))
	del l[0]
	for x in l:
		unite(n+x-1,i)
for i in range(n):
	if root(i)!=root(i+1):
		print("NO")
		exit()
print("YES")


h,w = map(int,input().split())
for i in range(h):
  s = list(map(str,input().split()))
  for j in range(w):
    if s[j] == "snuke":
      print(chr(j+65)+str(i+1))
      exit()

Score : <var>100</var> points

Problem Statement

There is a grid with <var>H</var> rows and <var>W</var> columns.

The square at the <var>i</var>-th row and <var>j</var>-th column contains a string <var>S_{i,j}</var> of length <var>5</var>.

The rows are labeled with the numbers from <var>1</var> through <var>H</var>, and the columns are labeled with the uppercase English letters from A through the <var>W</var>-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the <var>6</var>-th row and <var>8</var>-th column should be reported as H6.

Constraints

<var>1≦H, W≦26</var>

The length of <var>S_{i,j}</var> is <var>5</var>.

<var>S_{i,j}</var> consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

The input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>S_{1,1}</var> <var>S_{1,2}</var> <var>...</var> <var>S_{1,W}</var>
<var>S_{2,1}</var> <var>S_{2,2}</var> <var>...</var> <var>S_{2,W}</var>
<var>:</var>
<var>S_{H,1}</var> <var>S_{H,2}</var> <var>...</var> <var>S_{H,W}</var>

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


from string import *
h,w=map(int,input().split())

s=[None]*h
for i in range(h):
    s[i] = [None]*w
    for j in range(w):
        if(s[i][j]=='snuke'):
            idx1=ascii_lowercase[i].swapcase()
            idx2=str(j+1)
            print(idx1+idx2)
            exit()


import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def main():
    n,m = LI()
    xc = collections.Counter(LI())

    c = collections.defaultdict(int)
    d = collections.defaultdict(int)
    for x,v in xc.items():
        if v % 2 == 1:
            c[x % m] += 1
        d[x % m] += v

    r = d[0] // 2
    if m % 2 == 0:
        r += d[m // 2] // 2

    for i in range(1, (m+1)//2):
        t = min(d[i], d[m-i])
        r += t
        r += (d[i] - max(c[i], t)) // 2
        r += (d[m-i] - max(c[m-i], t)) // 2

    return r

print(main())

from collections import Counter
X,M = map(int, input().split())

A = list(map(int, input().split()))
C = Counter(A)
P = [0] * M # mod iの数
Q = [0] * M # mod iの同一数字のペアの数

for k,v in C.items():
  P[k % M] += v
  Q[k % M] += v//2

#print(P)
#print(Q)
ans = 0
for i in range(1,(M+1)//2):
  p1, p2 = P[i], P[M-i]
  q1, q2 = Q[i], Q[M-i]
  if p1 > p2:
    p1,p2 = p2,p1
    q1,q2 = q2,q1
  #print(ans, p1,p2,q1,q2)
  ans += p1
  ans += min((p2-p1)//2, q2)
ans += P[0] // 2
if M%2 == 0:
  ans += P[M//2] // 2

print(ans)

Score : <var>700</var> points

Problem Statement

Takahashi is playing with <var>N</var> cards.

The <var>i</var>-th card has an integer <var>X_i</var> on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of <var>M</var>.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

<var>2≦N≦10^5</var>

<var>1≦M≦10^5</var>

<var>1≦X_i≦10^5</var>

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>X_1</var> <var>X_2</var> <var>...</var> <var>X_N</var>

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs <var>(3,2), (1,4)</var> and <var>(1,9)</var> can be created.

It is possible to create pairs <var>(3,2)</var> and <var>(1,1)</var>, but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6


from collections import Counter
X,M = map(int, input().split())

A = list(map(int, input().split()))
C = Counter(A)
P = [0] * M # mod iの数
Q = [0] * M # mod iの同一数字のペアの数

for k,v in C.items():
  P[k % M] += v
  Q[k % M] += v//2

ans = 0
for i in range(M//2 + 1):
  if i == M:
    ans += P[i] // 2
  else:
    p1, p2 = P[i], P[M-i-1]
    q1, q2 = Q[i], Q[M-i-1]
    if p1 > p2:
      p1,p2 = p2,p1
      q1,q2 = q2,q1
    #print(ans, p1,p2,q1,q2)
    ans += p1
    ans += min((p2-p1)//2, q2)
if M%2 == 0:
  ans += P[M//2] // 2

print(ans)


class Tree():
    def __init__(self, n, edge, indexed=1):
        self.n = n
        self.tree = [[] for _ in range(n)]
        for e in edge:
            self.tree[e[0] - indexed].append(e[1] - indexed)
            self.tree[e[1] - indexed].append(e[0] - indexed)

    def setroot(self, root):
        self.root = root
        self.parent = [None for _ in range(self.n)]
        self.parent[root] = -1
        self.depth = [None for _ in range(self.n)]
        self.depth[root] = 0
        self.order = []
        self.order.append(root)
        stack = [root]
        while stack:
            node = stack.pop()
            for adj in self.tree[node]:
                if self.parent[adj] is None:
                    self.parent[adj] = node
                    self.depth[adj] = self.depth[node] + 1
                    self.order.append(adj)
                    stack.append(adj)

INF = 10**18

import sys
input = sys.stdin.readline

N = int(input())
E = [tuple(map(int, input().split())) for _ in range(N - 1)]

num = [None for _ in range(N)]

K = int(input())

for _ in range(K):
    v, p = map(int, input().split())
    num[v - 1] = p

tree = Tree(N, E)
tree.setroot(v - 1)

even = []
odd = []

for i in range(N):
    if num[i] is not None:
        if tree.depth[i] % 2 == 0:
            even.append(num[i] % 2)
        else:
            odd.append(num[i] % 2)

if not ((all(even) or not any(even)) and (all(odd) or not any(odd))):
    print('No')

else:
    I = [[-INF, INF] for _ in range(N)]
    for i in range(N):
        if num[i] is not None:
            I[i] = [num[i], num[i]]
    for node in tree.order[::-1]:
        lt, rt = I[node]
        for adj in tree.tree[node]:
            lt = max(lt, I[adj][0] - 1)
            rt = min(rt, I[adj][1] + 1)
        if lt > rt:
            print('No')
            break
        I[node] = [lt, rt]

    else:
        stack = [v - 1]
        visited = [0 for _ in range(N)]
        visited[v - 1] = 1
        while stack:
            node = stack.pop()
            for adj in tree.tree[node]:
                if visited[adj]:
                    continue
                visited[adj] = 1
                if I[adj][0] <= num[node] - 1 <= I[adj][1]:
                    num[adj] = num[node] - 1
                elif I[adj][0] <= num[node] + 1 <= I[adj][1]:
                    num[adj] = num[node] + 1
                else:
                    print('No')
                    break
                stack.append(adj)
            else:
                continue
            break
        else:
            print('Yes')
            print('\n'.join(map(str, num)))

import sys

sys.setrecursionlimit(10 ** 7)

def dfs(v, parent, odd):
    hi = INF
    lo = -INF
    if fixed[v] != INF:
        if odd_even[v] != odd:
            print('No')
            exit()
        hi = lo = fixed[v]
    for u in links[v]:
        if u == parent:
            continue
        chi, clo = dfs(u, v, odd ^ 1)
        if hi < clo or chi < lo:
            print('No')
            exit()
        hi = min(hi, chi)
        lo = max(lo, clo)
    upper[v] = hi
    lower[v] = lo
    return hi + 1, lo - 1

def fill(v, parent, pp):
    if pp + 1 > upper[v]:
        assert pp - 1 >= lower[v]
        vp = fixed[v] = pp - 1
    else:
        vp = fixed[v] = pp + 1
    for u in links[v]:
        if u == parent:
            continue
        fill(u, v, vp)

inp = list(map(int, sys.stdin.buffer.read().split()))
n = inp[0]
links = [set() for _ in range(n)]
for a, b in zip(inp[1:2 * n - 1:2], inp[2:2 * n - 1:2]):
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
INF = 10 ** 9
k = inp[2 * n - 1]
fixed = [INF] * n
odd_even = {}
fixed_v = 0
for v, p in zip(inp[2 * n::2], inp[2 * n + 1::2]):
    v -= 1
    fixed[v] = p
    odd_even[v] = p % 2
    fixed_v = v

lower = [-INF] * n
upper = [INF] * n
dfs(fixed_v, -1, odd_even[fixed_v])
fill(fixed_v, -1, fixed[fixed_v] + 1)
print('Yes')
print('\n'.join(map(str, fixed)))

Score : <var>800</var> points

Problem Statement

We have a tree with <var>N</var> vertices. The vertices are numbered <var>1, 2, ..., N</var>. The <var>i</var>-th (<var>1 ≦ i ≦ N - 1</var>) edge connects the two vertices <var>A_i</var> and <var>B_i</var>.

Takahashi wrote integers into <var>K</var> of the vertices. Specifically, for each <var>1 ≦ j ≦ K</var>, he wrote the integer <var>P_j</var> into vertex <var>V_j</var>. The remaining vertices are left empty. After that, he got tired and fell asleep.

Then, Aoki appeared. He is trying to surprise Takahashi by writing integers into all empty vertices so that the following condition is satisfied:

Condition: For any two vertices directly connected by an edge, the integers written into these vertices differ by exactly <var>1</var>.

Determine if it is possible to write integers into all empty vertices so that the condition is satisfied. If the answer is positive, find one specific way to satisfy the condition.

Constraints

<var>1 ≦ N ≦ 10^5</var>

<var>1 ≦ K ≦ N</var>

<var>1 ≦ A_i, B_i ≦ N</var> (<var>1 ≦ i ≦ N - 1</var>)

<var>1 ≦ V_j ≦ N</var> (<var>1 ≦ j ≦ K</var>) (21:18, a mistake in this constraint was corrected)

<var>0 ≦ P_j ≦ 10^5</var> (<var>1 ≦ j ≦ K</var>)

The given graph is a tree.

All <var>v_j</var> are distinct.

Input

The input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>B_1</var>
<var>A_2</var> <var>B_2</var>
<var>:</var>
<var>A_{N-1}</var> <var>B_{N-1}</var>
<var>K</var>
<var>V_1</var> <var>P_1</var>
<var>V_2</var> <var>P_2</var>
<var>:</var>
<var>V_K</var> <var>P_K</var>

Output

If it is possible to write integers into all empty vertices so that the condition is satisfied, print Yes. Otherwise, print No.

If it is possible to satisfy the condition, print <var>N</var> lines in addition. The <var>v</var>-th (<var>1 ≦ v ≦ N</var>) of these <var>N</var> lines should contain the integer that should be written into vertex <var>v</var>. If there are multiple ways to satisfy the condition, any of those is accepted.

Sample Input 1

5
1 2
3 1
4 3
3 5
2
2 6
5 7

Sample Output 1

Yes
5
6
6
5
7

The figure below shows the tree when Takahashi fell asleep. For each vertex, the integer written beside it represents the index of the vertex, and the integer written into the vertex is the integer written by Takahashi.

Aoki can, for example, satisfy the condition by writing integers into the remaining vertices as follows:

This corresponds to Sample Output 1. Note that other outputs that satisfy the condition will also be accepted, such as:

Yes
7
6
8
7
7

Sample Input 2

5
1 2
3 1
4 3
3 5
3
2 6
4 3
5 7

Sample Output 2

No

Sample Input 3

4
1 2
2 3
3 4
1
1 0

Sample Output 3

Yes
0
-1
-2
-3

The integers written by Aoki may be negative or exceed <var>10^6</var>.


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

INF = 10**10
n = int(input())
T = [[] for _ in range(n+1)]
for _ in range(n-1):
  a, b = map(int, input().split())
  T[a].append(b)
  T[b].append(a)
k = int(input())
VP = tuple(tuple(map(int, input().split())) for _ in range(k))
P = [-1]*(n+1)
A = [-1]*(n+1)
r, c = VP[0]
for v, p in VP:
  P[v] = p
def dfs1(v, par=-1, color=c%2):
  if P[v] == -1:
    l = -INF
    r = INF
  else:
    l = P[v]
    r = P[v]
  for nv in T[v]:
    if nv == par:
      continue
    nl, nr = dfs1(nv, v, color^1)
    l = max(l, nl-1)
    r = min(r, nr+1)
  if l&1 ^ color:
    l += 1
  if r&1 ^ color:
    r -= 1
  if l > r:
    print("No")
    exit()
  P[v] = (l, r)
  return P[v]
dfs1(r)
def dfs2(v, ini, par=-1):
  l, r = P[v]
  if l <= ini-1 <= r:
    A[v] = ini-1
  else:
    A[v] = ini+1
  for nv in T[v]:
    if nv == par:
      continue
    dfs2(nv, A[v], v)
dfs2(r, P[r][0])
print("Yes")
print(*A[1:], sep="\n")


a, b, c = map(int, input().split())

if a == b:
  if b == c:
    print(1)
  else:
    print(2)
elif b == c:
  print(2)
elif a == c:
  print(2)
else:
  print(3)

Score : <var>100</var> points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is <var>a</var>, the color of the one he bought yesterday is <var>b</var>, and the color of the one he bought today is <var>c</var>.
Here, the color of each paint can is represented by an integer between <var>1</var> and <var>100</var>, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

<var>1≦a,b,c≦100</var>

Input

The input is given from Standard Input in the following format:

<var>a</var> <var>b</var> <var>c</var>

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: <var>1</var>, <var>3</var>, and <var>4</var>.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: <var>3</var> and <var>33</var>.


a, b, c = map(int, input().split())

if a == b:
  if b == c:
    print(1)
  else:
    print(2)
elif b == c:
  print(2)
else:
  print(3)


S = input()
T = "CODEFESTIVAL2016"
ans = 0
for i in range(len(S)):
    if S[i] != T[i]:
        ans += 1
print(ans)

S = input()
T = 'CODEFESTIVAL2016'

ans = 0
for i in range(len(S)):
    if S[i] != T[i]:
        ans += 1
print(ans)

Score : <var>100</var> points

Problem Statement

CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.

He intended to write CODEFESTIVAL2016 on it, but he mistakenly wrote a different string <var>S</var>. Fortunately, the string he wrote was the correct length.

So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to CODEFESTIVAL2016.

Find the minimum number of iterations for the rewrite operation.

Constraints

<var>S</var> is <var>16</var> characters long.

<var>S</var> consists of uppercase and lowercase alphabet letters and numerals.

Input

Inputs are provided from Standard Input in the following form.

<var>S</var>

Output

Output an integer representing the minimum number of iterations needed for the rewrite operation.

Sample Input 1

C0DEFESTIVAL2O16

Sample Output 1

2

The second character 0 must be changed to O and the <var>14</var>th character O changed to 0.

Sample Input 2

FESTIVAL2016CODE

Sample Output 2

16


s = input()
sum(a!=b for a, b in zip(s, 'CODEFESTIVAL2016'))


import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
A = [int(input()) for _ in range(N)]

ans = A[0] - 1
p = 2

i = 1
while i < N:
    a = A[i]
    if a == p:
        p += 1
    else:
        ans += (a - 1) // p
    i += 1

print(ans)

I,A=input,int
n=A(I())
a=[A(I())for i in range(n)]
L,C=a[0]-1,2
for i in a[1:]:
 if i==C:C+=1
 L+=(i-1)//C
print(L)

Score : <var>700</var> points

Problem Statement

<var>N</var> people are waiting in a single line in front of the Takahashi Store. The cash on hand of the <var>i</var>-th person from the front of the line is a positive integer <var>A_i</var>.

Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer <var>P</var> indicating its price, and shows this product to customers in order, starting from the front of the line. This step is repeated as described below.

At each step, when a product is shown to a customer, if price <var>P</var> is equal to or less than the cash held by that customer at the time, the customer buys the product and Mr. Takahashi ends the current step. That is, the cash held by the first customer in line with cash equal to or greater than <var>P</var> decreases by <var>P</var>, and the next step begins.

Mr. Takahashi can set the value of positive integer <var>P</var> independently at each step.

He would like to sell as many products as possible. However, if a customer were to end up with <var>0</var> cash on hand after a purchase, that person would not have the fare to go home. Customers not being able to go home would be a problem for Mr. Takahashi, so he does not want anyone to end up with <var>0</var> cash.

Help out Mr. Takahashi by writing a program that determines the maximum number of products he can sell, when the initial cash in possession of each customer is given.

Constraints

<var>1 ≦ | N | ≦ 100000</var>

<var>1 ≦ A_i ≦ 10^9(1 ≦ i ≦ N)</var>

All inputs are integers.

Input

Inputs are provided from Standard Inputs in the following form.

<var>N</var>
<var>A_1</var>
:
<var>A_N</var>

Output

Output an integer representing the maximum number of products Mr. Takahashi can sell.

Sample Input 1

3
3
2
5

Sample Output 1

3

As values of <var>P</var>, select in order <var>1, 4, 1</var>.

Sample Input 2

15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 2

18


N = int(input())
*A, = [int(input()) for _ in range(N)]

ans = 0
v = 0

for i, j in enumerate(A):
    if j==v+1:
        v += 1
    ans += (j-1)//(v+1)

print(ans)


code = r"""
# distutils: language=c++
# cython: wraparound=False
from libcpp.set cimport set
from libcpp.vector cimport vector
from libc.stdio cimport getchar, printf
from cython.operator cimport dereference as deref
from cython.operator cimport preincrement as preinc, predecrement as predec
from cython.operator cimport postincrement as postinc, postdecrement as postdec
cdef int cin() nogil:
    cdef int b, c = 0
    while 1:
        b = getchar() - 48
        if b < 0: break
        c = c * 10 + b
    return c
cdef int n = cin(), i
cdef long c
cdef vector[long] a = vector[long](n)
for i in range(n): a[cin() - 1] = i
cdef set[long] s = set[long]([-1, n])
cdef set[long].iterator it
for i in range(n):
    it = s.lower_bound(a[i])
    c += (deref(postdec(it)) - a[i]) * (a[i] - deref(it)) * (i + 1)
    s.insert(a[i])
printf('%ld\n', c)
"""
import os, sys
if sys.argv[-1] == 'ONLINE_JUDGE':
    open('solve.pyx', 'w').write(code)
    os.system('cythonize -i -3 -b solve.pyx')
import solve

code = r"""
# distutils: language=c++
# cython: boundscheck=False, wraparound=False
from libcpp.set cimport set
from libcpp.vector cimport vector
from libc.stdio cimport getchar, printf
from cython.operator cimport dereference as deref
from cython.operator cimport preincrement as preinc, predecrement as predec
from cython.operator cimport postincrement as postinc, postdecrement as postdec
cdef int cin() nogil:
    cdef int b, c = 0
    while 1:
        b = getchar() - 48
        if b < 0: break
        c = c * 10 + b
    return c
cdef int n = cin(), i
cdef long c
cdef vector[long] a = vector[long](n)
for i in range(n): a[cin() - 1] = i
cdef set[long] s = set[long]([-1, n])
cdef set[long].iterator it
for i in range(n):
    it = s.lower_bound(a[i])
    c += (deref(postdec(it)) - a[i]) * (a[i] - deref(it)) * (i + 1)
    s.insert(a[i])
printf('%ld\n', c)
"""
import os, sys
if sys.argv[-1] == 'ONLINE_JUDGE':
    open('solve.pyx', 'w').write(code)
    os.system('cythonize -i -3 -b solve.pyx')
import solve

Score : <var>400</var> points

Problem Statement

One day, Snuke was given a permutation of length <var>N</var>, <var>a_1, a_2, ..., a_N</var>, from his friend.

Find the following:

Constraints

<var>1 ≦ N ≦ 200,000</var>

<var>(a_1, a_2, ..., a_N)</var> is a permutation of <var>(1, 2, ..., N)</var>.

Input

The input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_N</var>

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


1 / (not ' ' in input())
1 / (not '  ' in input())


s = list(input())
k = int(input())
ls = list("abcdefghijklmnopqrstuvwxyz")
ls.sort(reverse=True)
ls = ["a"] + ls[:-1]
for i in range(len(s)):
    if i != len(s)-1:
        if k >= ls.index(s[i]):
            k -= ls.index(s[i])
            s[i] = "a"
        else:
            continue
    else:
        k %= 26
        s[-1] = ls[(ls.index(s[-1])-k)%26]
print("".join(s))

import sys
import itertools
# import numpy as np
import time
import math
from heapq import heappop, heappush
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import permutations
sys.setrecursionlimit(10 ** 7)

INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
S = input()
K = int(input())

ans = []
for i, c in enumerate(S):
    if c == 'a':
        ans.append(c)
        continue
    num = ord('z') - ord(c) + 1
    if K >= num:
        K -= num
        ans.append('a')
    else:
        ans.append(c)
if K > 0:
    ans[-1] = chr((ord(ans[-1]) - ord('a') + K % 26) % 26 + ord('a'))
print("".join(ans))

Score : <var>400</var> points

Problem Statement

Mr. Takahashi has a string <var>s</var> consisting of lowercase English letters.
He repeats the following operation on <var>s</var> exactly <var>K</var> times.

Choose an arbitrary letter on <var>s</var> and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly <var>K</var> operations on <var>s</var>.
Find the such string.

Constraints

<var>1≤|s|≤10^5</var>

All letters in <var>s</var> are lowercase English letters.

<var>1≤K≤10^9</var>

Input

The input is given from Standard Input in the following format:

<var>s</var>
<var>K</var>

Output

Print the lexicographically smallest string after performing exactly <var>K</var> operations on <var>s</var>.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly <var>K</var> operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


import sys
import itertools
# import numpy as np
import time
import math
from heapq import heappop, heappush
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import permutations
sys.setrecursionlimit(10 ** 7)

INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
S = input()
K = int(input())

ans = []
for i, c in enumerate(S[:-1]):
    num = ord('z') - ord(c) + 1
    if K >= num:
        K -= num
        ans.append('a')
    else:
        ans.append(c)
# if K > 0:
ans.append(chr((ord(S[-1]) - ord('a') + K) % 26 + ord('a')))
print("".join(ans))


import sys

sys.setrecursionlimit(10 ** 6)

def dfs(links, n, k, v, p):
    height_from_leaf = 0
    cut_count = 0
    for u in links[v]:
        if u == 0:
            continue
        hgt, cut = dfs(links, n, k, u, v)
        height_from_leaf = max(height_from_leaf, hgt)
        cut_count += cut
    height_from_leaf += 1
    if p != 0 and height_from_leaf == k:
        height_from_leaf = 0
        cut_count += 1
    return height_from_leaf, cut_count

n, k, *aaa = map(int, sys.stdin.buffer.read().split())
links = [set() for _ in range(n)]
for i, a in enumerate(aaa):
    a -= 1
    links[a].add(i)
_, ans = dfs(links, n, k, 0, 0)
if aaa[0] != 1:
    ans += 1

print(ans)

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

n, k = map(int, input().split())
A = list(map(int, input().split()))
ans = 0
if A[0] != 1:
  ans += 1
C = [[] for _ in range(n+1)]
P = [-1]*(n+1)
for i, a in enumerate(A[1:], 2):
  C[a].append(i)
  P[i] = a
def dfs(v):
  global ans
  temp = 0
  for nv in C[v]:
    temp = max(temp, dfs(nv)+1)
  if v == 1:
    return
  if P[v] != 1 and temp == k-1:
    temp = -1
    ans += 1
  return temp
dfs(1)
print(ans)

Score : <var>800</var> points

Problem Statement

There are <var>N</var> towns in Snuke Kingdom, conveniently numbered <var>1</var> through <var>N</var>.
Town <var>1</var> is the capital.

Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place.
The destination of the Teleporter of town <var>i</var> is town <var>a_i</var> (<var>1≤a_i≤N</var>).
It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.

King Snuke loves the integer <var>K</var>.
The selfish king wants to change the destination of the Teleporters so that the following holds:

Starting from any town, one will be at the capital after using the Teleporters exactly <var>K</var> times in total.

Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.

Constraints

<var>2≤N≤10^5</var>

<var>1≤a_i≤N</var>

One can get to the capital from any town by using the Teleporters some number of times.

<var>1≤K≤10^9</var>

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_N</var>

Output

Print the minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.

Sample Input 1

3 1
2 3 1

Sample Output 1

2

Change the destinations of the Teleporters to <var>a = (1,1,1)</var>.

Sample Input 2

4 2
1 1 2 2

Sample Output 2

0

There is no need to change the destinations of the Teleporters, since the king's desire is already satisfied.

Sample Input 3

8 2
4 1 2 3 1 2 3 4

Sample Output 3

3

For example, change the destinations of the Teleporters to <var>a = (1,1,2,1,1,2,2,4)</var>.


from sys import stdin
input = stdin.readline
n, k = map(int, input().split())
aa = list(map(int, input().split()))
print(0)


n, a = map(int, input().split())
xlst = list(map(int, input().split()))
dp = [[0 for _ in range(5001)] for _ in range(n + 1)]
center = 2500
dp[0][center] = 1
for i, x in enumerate(xlst, 1):
    num = x - a
    for j in range(5001):
        dp[i][j] = dp[i - 1][j]
        if 0 <= j - num <= 5000:
            dp[i][j] += dp[i - 1][j - num]
print(dp[-1][center] - 1)

n, a = map(int, input().split())
l = list(map(int, input().split()))
ans = 0
dp = list([0]*(n*a+1) for _ in range(n+1))#動的計画法で解く
dp[0][0] = 1
for x in l:
    for i in range(n, 0, -1):#下行から順に格納していく(上からだと格納したばかりの値が参照されてしまう)
        for j in range(n*a+1):
            if x > j:
                continue
            dp[i][j] += dp[i-1][j-x]

for i in range(n):
    ans += dp[i+1][(i+1)*a]

print(ans)

Score : <var>300</var> points

Problem Statement

Tak has <var>N</var> cards. On the <var>i</var>-th <var>(1 \leq i \leq N)</var> card is written an integer <var>x_i</var>.
He is selecting one or more cards from these <var>N</var> cards, so that the average of the integers written on the selected cards is exactly <var>A</var>.
In how many ways can he make his selection?

Constraints

<var>1 \leq N \leq 50</var>

<var>1 \leq A \leq 50</var>

<var>1 \leq x_i \leq 50</var>

<var>N,\,A,\,x_i</var> are integers.

Partial Score

<var>200</var> points will be awarded for passing the test set satisfying <var>1 \leq N \leq 16</var>.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>A</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Output

Print the number of ways to select cards such that the average of the written integers is exactly <var>A</var>.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the <var>5</var> ways to select cards such that the average is <var>8</var>:

Select the <var>3</var>-rd card.

Select the <var>1</var>-st and <var>2</var>-nd cards.

Select the <var>1</var>-st and <var>4</var>-th cards.

Select the <var>1</var>-st, <var>2</var>-nd and <var>3</var>-rd cards.

Select the <var>1</var>-st, <var>3</var>-rd and <var>4</var>-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a <var>32</var>-bit integer.


n,a = map(int,input().split())
x = list(map(int,input().split()))

dp = [[[0]*(55) for i in range(3000)]for i in range(55)]
dp[0][0][0] = 1

for i in range(n):
  for j in range(n*a):
    for k in range(n):
      dp[i+1][j][k] += dp[i][j][k]
      dp[i+1][j+x[i]][k+1] += dp[i][j][k]

ans = 0
for k in range(1,n):
  ans += dp[n][k*a][k]
print(ans)


import sys
input = sys.stdin.readline

def digit_sum(n, b):
    res = 0
    while n > 0:
        res += n % b
        n //= b
    return res

def main():
    n = int(input())
    s = int(input())
    ans = -1

    if n < s:
        ans = -1

    elif n == s:
        ans = n + 1

    else:
        key = []
        start, first = n, 1

        for i in range(1, n):
            first = digit_sum(n, start)
            end = start - n // i // (i + 1)
            if start == end+1:
                judge = start
                break

            while end > 1:
                if digit_sum(n, end) == i * (start - end) + first:
                    end -= 1
                    continue
                break
            next_start = end
            value = digit_sum(n, start)
            end = value + (start - end - 1) * i
            key.append((start, value, end, i, first))
            judge = start
            start = next_start
            if start == 1:
                break

        for i in range(2, judge + 1):
            sub = digit_sum(n, i)
            if sub == s:
                ans = i
                break
        else:
            for index, start, end, i, first in reversed(key):
                if end < s or s < start:
                    continue
                if (s - start) % i:
                    continue
                ans = index - (s - first) // i
                break

    print(ans)

if __name__ == "__main__":
    main()

import sys
input = sys.stdin.readline

def digit_sum(n, b):
    if b == 1:
        return n
    res = 0
    while n > 0:
        res += n % b
        n //= b
    return res

def main():
    n = int(input())
    s = int(input())

    ans = -1
    if n == s:
        ans = n + 1
    else:
        for b in range(2, int(n**0.5) + 1):
            if digit_sum(n, b) == s:
                ans = b
                break

        else:
            for p in range(1, int(n**0.5)+1):
                b = (n - s) // p + 1
                if b >= 2 and digit_sum(n, b) == s:
                    if ans == -1:
                        ans = b
                    else:
                        ans = min(ans, b)

                if b >= 1 and digit_sum(n, b+1) == s:
                    if ans == -1:
                        ans = b+1
                    else:
                        ans = min(ans, b+1)

    print(ans)

if __name__ == "__main__":
    main()

Score : <var>500</var> points

Problem Statement

For integers <var>b (b \geq 2)</var> and <var>n (n \geq 1)</var>, let the function <var>f(b,n)</var> be defined as follows:

<var>f(b,n) = n</var>, when <var>n < b</var>

<var>f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b)</var>, when <var>n \geq b</var>

Here, <var>{\rm floor}(n / b)</var> denotes the largest integer not exceeding <var>n / b</var>,
and <var>n \ {\rm mod} \ b</var> denotes the remainder of <var>n</var> divided by <var>b</var>.

Less formally, <var>f(b,n)</var> is equal to the sum of the digits of <var>n</var> written in base <var>b</var>.
For example, the following hold:

<var>f(10,\,87654)=8+7+6+5+4=30</var>

<var>f(100,\,87654)=8+76+54=138</var>

You are given integers <var>n</var> and <var>s</var>.
Determine if there exists an integer <var>b (b \geq 2)</var> such that <var>f(b,n)=s</var>.
If the answer is positive, also find the smallest such <var>b</var>.

Constraints

<var>1 \leq n \leq 10^{11}</var>

<var>1 \leq s \leq 10^{11}</var>

<var>n,\,s</var> are integers.

Input

The input is given from Standard Input in the following format:

<var>n</var>
<var>s</var>

Output

If there exists an integer <var>b (b \geq 2)</var> such that <var>f(b,n)=s</var>, print the smallest such <var>b</var>.
If such <var>b</var> does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


import sys
input = sys.stdin.readline

def digit_sum(n, b):
    res = 0
    while n > 0:
        res += n % b
        n //= b
    return res

def main():
    n = int(input())
    s = int(input())
    ans = -1

    if n < s:
        ans = -1

    elif n == s:
        ans = n + 1

    else:
        key = []
        start, first = n, 1

        for i in range(1, n):
            first = digit_sum(n, start)
            end = start - n // i // (i + 1)
            if start == end+1:
                judge = start
                break

            while end > 1:
                if digit_sum(n, end) == i * (start - end) + first:
                    end -= 1
                    continue
                break

            next_start = end
            value = digit_sum(n, start)
            key.append((start, value, end+1, i, first))
            judge = start
            start = next_start
            if start == 1:
                break

        for i in range(2, judge + 1):
            sub = digit_sum(n, i)
            if sub == s:
                ans = i
                break
        else:
            for index, start, end, i, first in reversed(key):
                if end < s or s < start:
                    continue
                if (s - first) % i:
                    continue
                ans = index - (s - first) // i
                break

    print(ans)

if __name__ == "__main__":
    main()


n,m = [int(x) for x in input().split()]
x = []
for i in range(m):
  x.append([int(x) for x in input().split()])
count = [1] * (n+1)
flag = [0] * (n+1)
flag[1] = 1
for i in range(m):
  if flag[x[i][0]] == 1:
    flag[x[i][1]] = 1
  if count[x[i][0]] == 1:
    flag[x[i][0]] = 0
  count[x[i][0]] -= 1
  count[x[i][1]] += 1

res = 0
for i in range(n+1):
  if flag[i] == 1:
    res += 1

print(res)

import numpy as np

N,M=map(int,input().split())
length=np.ones(N+1)
aka=np.ones(N+1)
aka[1]=-1

for _ in range(M):
  x,y=map(int,input().split())
  if aka[x]==-1:
    aka[y]=-1
  if length[x]-1==0:
    aka[x]=1
  length[x]-=1
  length[y]+=1

print(len(aka[aka<0]))

Problem Statement

We have <var>N</var> boxes, numbered <var>1</var> through <var>N</var>. At first, box <var>1</var> contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following <var>M</var> operations, one by one. In the <var>i</var>-th operation, he randomly picks one ball from box <var>x_i</var>, then he puts it into box <var>y_i</var>.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

<var>2≤N≤10^5</var>

<var>1≤M≤10^5</var>

<var>1≤x_i,y_i≤N</var>

<var>x_i≠y_i</var>

Just before the <var>i</var>-th operation is performed, box <var>x_i</var> contains at least <var>1</var> ball.

Input

The input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_M</var> <var>y_M</var>

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box <var>1</var> is empty, box <var>2</var> contains one red ball and one white ball, and box <var>3</var> contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box <var>2</var>, the red ball will go into box <var>3</var>. If he picks the white ball instead, the red ball will stay in box <var>2</var>.
Thus, the number of boxes that may contain the red ball after all operations, is <var>2</var>.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box <var>3</var>.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


from collections import defaultdict
n, m = map(int, input().split())
r = set()
r.add(1)
d = defaultdict(int)
for i in range(m):
  x, y = map(int, input().split())
  d[x] -= 1
  d[y] += 1
  if x in r:
    r.add(y)
ans = len(list(r))
for e in d:
  if d[e] == -1 and e in r:
    ans -= 1
print(ans)