input
stringlengths 20
127k
| target
stringlengths 20
119k
| problem_id
stringlengths 6
6
|
---|---|---|
n, x, m = list(map(int, input().split()))
arr = [x]
mod = x
def find_value(lst, value):
return [i for i, x in enumerate(lst) if x == value]
ans = 0
for i in range(n-1):
mod = mod ** 2 % m
res = find_value(arr, mod)
if res:
j = res[0]
a = i + 1 - j
q, mod = divmod((n - j), a)
ans = sum(arr[0:j]) + q * sum(arr[j:j+a]) + sum(arr[j:j+mod])
break
arr.append(mod)
if ans == 0:
ans = sum(arr)
print(ans)
|
n, x, m = list(map(int, input().split()))
arr = [x]
mod = x
memo = [-1 for _ in range(m+1)]
ans = 0
for i in range(1, n):
mod = mod ** 2 % m
idx = memo[mod]
if idx != -1:
a = i - idx
q, _mod = divmod((n - idx), a)
ans = sum(arr[0:idx]) + q * sum(arr[idx:idx+a]) + sum(arr[idx:idx+_mod])
break
arr.append(mod)
memo[mod] = i
if ans == 0:
ans = sum(arr)
print(ans)
|
p02550
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
class Doubling():
def __init__(self, a0, M):
"""
a0 is an array-like object which contains ai, 0 <= i < N.
ai is the next value of i.
"""
N = len(a0)
self.N = N
self.nt = [[None] * N for i in range(M.bit_length()+1)]
for i, a in enumerate(a0):
self.nt[0][i] = a
for i in range(1, len(self.nt)):
for j in range(N):
if self.nt[i-1][j] is None:
self.nt[i][j] = None
else:
self.nt[i][j] = self.nt[i-1][self.nt[i-1][j]]
def apply(self, i, n):
"""
Apply n times from i
"""
j = i
for k in range(n.bit_length()):
m = 1 << k
if m & n:
j = self.nt[k][j]
if j is None:
break
return j
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
if math.gcd(X, M) != 1:
for _ in range(N):
ans += x
x *= x
x %= M
if x == 0:
break
return ans
else:
x = X
s = [X]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
# if math.gcd(X, M) != 1:
if False:
for _ in range(N):
ans += x
x *= x
x %= M
if x == 0:
break
return ans
else:
x = X
s = [X]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
# N = 10**10
# X = random.randint(1, 10**5)
# M = random.randint(1, 10**5)
# N, X, M = 10000000000, 82162, 79872
# print(N, X, M)
# print(slv(N, X, M))
if __name__ == '__main__':
main()
|
p02550
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
# if math.gcd(X, M) != 1:
if False:
for _ in range(N):
ans += x
x *= x
x %= M
if x == 0:
break
return ans
else:
x = X
s = [X]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
# N = 10**10
# X = random.randint(1, 10**5)
# M = random.randint(1, 10**5)
# N, X, M = 10000000000, 82162, 79872
# print(N, X, M)
# print(slv(N, X, M))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
x = X
s = [X]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
if __name__ == '__main__':
main()
|
p02550
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
x = X
s = [X]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, X, M):
ans = 0
x = X
x %= M
s = [x]
u = set()
while True:
x *= x
x %= M
s.append(x)
if x in u:
break
u.add(x)
i = s.index(s[-1])
if i + 1 >= N:
return sum(s[:N]) % M
N -= i
ans += sum(s[:i])
s = s[i:]
s.pop()
ss = sum(s)
ans += (N // len(s)) * ss
ans += sum(s[:N%len(s)])
return ans
def main():
N, X, M = read_int_n()
print(slv(N, X, M))
if __name__ == '__main__':
main()
|
p02550
|
n,x,m = list(map(int, input().split()))
amari = [x]
cnt = 0
p = 0
for i in range(n-1):
a = amari[-1]**2 % m
if a in amari:
p = amari.index(a)
cnt = i+1-p
break
else:
amari.append(a)
if cnt == 0:
print((sum(amari)))
else:
n -= len(amari)
a = n // cnt
b = n % cnt
print((sum(amari)+a*sum(amari[p:])+sum(amari[p:(p+b)])))
|
n,x,m = list(map(int, input().split()))
amari = [x]
amariset = {x}
cnt = 0
p = 0
for i in range(n-1):
a = amari[-1]**2 % m
if a in amariset:
p = amari.index(a)
cnt = i+1-p
break
else:
amari.append(a)
amariset.add(a)
if cnt == 0:
print((sum(amari)))
else:
n -= len(amari)
a = n // cnt
b = n % cnt
print((sum(amari)+a*sum(amari[p:])+sum(amari[p:(p+b)])))
|
p02550
|
N, X, M = list(map(int, input().split()))
used = [0] * M
a = []
A = X
for i in range(N):
if used[A] != 0:
break
used[A] = 1
a.append(A)
A = A * A % M
for i in range(len(a)):
if a[i] == A:
break
j = i
if a[-1] != 0:
result = sum(a[:j])
a = a[j:]
l = len(a)
x = (N - j) // l
y = (N - j) - x * l
s = sum(a)
result += s * x
result += sum(a[:y])
print(result)
else:
s = sum(a)
print(s)
|
N, X, M = list(map(int, input().split()))
existence = [0] * M
a = []
A = X
for i in range(N):
if existence[A] != 0:
break
existence[A] = 1
a.append(A)
A = A * A % M
for i in range(len(a)):
if a[i] == A:
break
j = i
result = sum(a[:j])
a = a[j:]
N -= j
x = N // len(a)
y = N % len(a)
result += sum(a) * x + sum(a[:y])
print(result)
|
p02550
|
N, X, M = list(map(int, input().split()))
existence = [False] * M
a = []
A = X
for i in range(N):
if existence[A]:
break
existence[A] = True
a.append(A)
A = A * A % M
for i in range(len(a)):
if a[i] == A:
break
loop_start = i
result = sum(a[:loop_start])
a = a[loop_start:]
N -= loop_start
loops = N // len(a)
remainder = N % len(a)
result += sum(a) * loops + sum(a[:remainder])
print(result)
|
N, X, M = list(map(int, input().split()))
existence = [False] * M
a = []
A = X
for i in range(N):
if existence[A]:
break
existence[A] = True
a.append(A)
A = A * A % M
for i in range(len(a)):
if a[i] == A:
loop_start = i
break
else:
loop_start = len(a)
result = sum(a[:loop_start])
a = a[loop_start:]
N -= loop_start
if N != 0:
loops = N // len(a)
remainder = N % len(a)
result += sum(a) * loops + sum(a[:remainder])
print(result)
|
p02550
|
N, X, M = list(map(int, input().split()))
existence = [False] * M
a = []
A = X
for i in range(N):
if existence[A]:
break
existence[A] = True
a.append(A)
A = A * A % M
for i in range(len(a)):
if a[i] == A:
loop_start = i
break
else:
loop_start = len(a)
result = sum(a[:loop_start])
N -= loop_start
if N != 0:
a = a[loop_start:]
loops = N // len(a)
remainder = N % len(a)
result += sum(a) * loops + sum(a[:remainder])
print(result)
|
N, X, M = list(map(int, input().split()))
existence = [False] * M
a = []
A = X
for i in range(N):
if existence[A]:
break
existence[A] = True
a.append(A)
A = A * A % M
try:
loop_start = a.index(A)
except:
loop_start = len(a)
result = sum(a[:loop_start])
N -= loop_start
if N != 0:
a = a[loop_start:]
loops = N // len(a)
remainder = N % len(a)
result += sum(a) * loops + sum(a[:remainder])
print(result)
|
p02550
|
n,x,m = list(map(int, input().split()))
ans = 0
x_list = []
for _ in range(n):
x_list.append(x)
ans += x
x = x**2 % m
if x == 0:
ans = sum(x_list)
break
if x == 1:
ans = sum(x_list) + (n-len(x_list))
break
if x_list.count(x) == 1:
after_list = x_list[x_list.index(x):(len(x_list))]
if x_list.index(x) == 0:
if (n // len(x_list)) == 0:
ans = sum(x_list) * (n // len(x_list))
else:
ans = sum(x_list) * (n // len(x_list)) + sum(x_list[0:((n % len(x_list)))])
else:
if (n-x_list.index(x)) % len(after_list) == 0:
ans = sum(after_list) * ((n-x_list.index(x)) // len(after_list)) + sum(x_list[0:(x_list.index(x))])
else:
ans = sum(after_list) * ((n-x_list.index(x)) // len(after_list)) + sum(after_list[0:(((n-x_list.index(x)) % len(after_list)))]) + sum(x_list[0:(x_list.index(x))])
break
print(ans)
|
N, X, M = list(map(int, input().split()))
def next_f(a):
return a * a % M
visited = [None] * M
sum_at_visit = [None] * M
loop_done = False
time = 1
ans = 0
x = X
while time <= N:
if not loop_done and visited[x] is not None:
# found cycle
loop_len = time - visited[x]
loop_sum = ans + x - sum_at_visit[x]
loops = (N-loop_len-time) // loop_len
time += loop_len * loops
ans += loop_sum * loops
loop_done = True
ans += x
visited[x] = time
sum_at_visit[x] = ans
time += 1
x = next_f(x)
print(ans)
|
p02550
|
n,x,m = list(map(int, input().split()))
ans = 0
x_list = []
for _ in range(min(10**5,n)):
x_list.append(x)
ans += x
x = x**2 % m
if x_list.count(x) == 1:
after_list = x_list[x_list.index(x):(len(x_list))]
if x_list.index(x) == 0:
if (n // len(x_list)) == 0:
ans = ans * (n // len(x_list))
else:
ans = ans * (n // len(x_list)) + sum(x_list[0:((n % len(x_list)))])
else:
if (n-x_list.index(x)) % len(after_list) == 0:
ans = (ans - sum(x_list[0:(x_list.index(x))])) * ((n-x_list.index(x)) // len(after_list)) + sum(x_list[0:(x_list.index(x))])
else:
ans = (ans - sum(x_list[0:(x_list.index(x))])) * ((n-x_list.index(x)) // len(after_list)) + sum(after_list[0:(((n-x_list.index(x)) % len(after_list)))]) + sum(x_list[0:(x_list.index(x))])
break
print(ans)
|
N,x,M=list(map(int,input().split()))
k=x
L=list()
c=dict()
for i in range(M):
if i==N:
print((sum(L)))
exit()
if x==0:
print((sum(L)))
exit()
L.append(x)
x=(x*x)%M
if x in c:
q=x
break
c[x]=1
moto=sum(L)
N-=len(L)
for i in range(len(L)):
if L[i]==q:
roop=list(L[i:])
L=roop
a=len(L)
if N%a==0:
print((moto+(sum(L)*(N//a))))
else:
s=N//a
t=N%a
ans=sum(L)*s
ans+=sum(roop[:t])
print((moto+ans))
|
p02550
|
def f(x, m):
return (x ** 2) % m
def main():
n, x, m = list(map(int, input().split()))
lst = [[False, 0] for _ in range((m + 1))]
lst[x] = [True, 1]
res = [x]
loop = 0
for i in range(2, m + 1):
x = f(x, m)
if lst[x][0] == False:
lst[x][0] = True
lst[x][1] = i
res.append(x)
else:
loop = i - lst[x][1]
non_loop = lst[x][1] - 1
break
if loop == 0:
print((sum(res[:n])))
exit()
ans = sum(res[:non_loop])
ans += (n - non_loop) // loop * sum(res[non_loop:])
ans += sum(res[non_loop:non_loop + (n - non_loop) % loop])
print(ans)
if __name__ == "__main__":
main()
|
def main():
n, x, m = list(map(int, input().split()))
idx = [-1] * (m + 1) # mで割った余り(0,1,...m-1)が何回目に出てきたか
res = [] # 数列A
for i in range(1, m + 3): # 余りはm+1種類なのでm+2回計算すれば絶対ループが発生する
if idx[x] == -1: # 初めて
idx[x] = i
res.append(x)
else: # 既出(ループ発見)
len_loop = i - idx[x]
len_head = idx[x] - 1
break
x = (x ** 2) % m
if n <= len_head + len_loop: # 1ループ目までで出力する場合
print((sum(res[:n])))
else:
ans = sum(res[:len_head]) # ループ前
ans += (n - len_head) // len_loop * sum(res[len_head:]) # ループ
ans += sum(res[len_head: len_head + (n - len_head) %
len_loop]) # ループ後の余り
print(ans)
if __name__ == "__main__":
main()
|
p02550
|
def cycle_getter(N, start):
"""
:param N: 移動回数
:param start: 初期条件
:return front: cycleまでの要素のリスト
cycle: cycle内の要素のリスト
end: cycle後の余った部分の要素のリスト
cnt: cycle回数
"""
p = start
front, cycle, end = [], [], []
cnt = 0
visit = {p:0}
L, R = N, -1
for i in range(1,N):
p = lift(p)
if p in visit:
"""
(L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
[6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
"""
L, R = visit[p], i
period = R-L
break
visit[p] = i
p = start
for _ in range(L):
front.append(p)
p = lift(p)
if L != N:
for _ in range(L,R):
cycle.append(p)
p = lift(p)
for _ in range(N-(N-L)%period,N):
end.append(p)
p = lift(p)
cnt = (N-L)//period
return front, cycle, end, cnt
def lift(x): return pow(x,2,M)
################################################################################
import sys
input = sys.stdin.readline
N, X, M = list(map(int, input().split()))
front, cycle, end, cnt = cycle_getter(N,X)
print((sum(front)+sum(cycle)*cnt+sum(end)))
|
def cycle_getter(N, start):
"""
:param N: 移動回数
:param start: 初期条件
:return front: cycleまでの要素のリスト
cycle: cycle内の要素のリスト
end: cycle後の余った部分の要素のリスト
cnt: cycle回数
"""
p = start
front, cycle, end = [], [], []
cnt = 0
visit = {p:0}
L, R = N, -1
P = [p]
for i in range(1,N):
p = lift(p)
if p in visit:
"""
(L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
[6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
"""
L, R = visit[p], i
period = R-L
break
visit[p] = i
P.append(p)
front = P[:L]
if L != N:
cycle, end = P[L:R], P[L:L+(N-L)%period]
cnt = (N-L)//period
return front, cycle, end, cnt
################################################################################
import sys
input = sys.stdin.readline
def lift(x): return pow(x,2,M)
N, X, M = list(map(int, input().split()))
front, cycle, end, cnt = cycle_getter(N,X)
# print(front, cycle, end, cnt)
print((sum(front)+sum(cycle)*cnt+sum(end)))
|
p02550
|
# -*- coding: utf-8 -*-
# 標準入力を取得
N, X, M = list(map(int, input().split()))
# 求解処理
def f(x: int, m: int) -> int:
return x**2 % m
A = [X]
loop_start_index = 0
while True:
A_next = f(A[-1], M)
if A_next in A:
loop_start_index = A.index(A_next)
break
else:
A.append(A_next)
loop_length = len(A) - loop_start_index
loop_cnt = (N - loop_start_index) // loop_length
loop_res = (N - loop_start_index) % loop_length
ans = sum(A[:loop_start_index]) + loop_cnt * sum(A[loop_start_index:]
) + sum(A[loop_start_index: loop_start_index + loop_res])
# 結果出力
print(ans)
|
# -*- coding: utf-8 -*-
# 標準入力を取得
N, X, M = list(map(int, input().split()))
# 求解処理
def f(x: int, m: int) -> int:
return x**2 % m
A = [X]
s = {X}
i = 0
while True:
A_next = f(A[-1], M)
if A_next in s:
i = A.index(A_next)
break
else:
A.append(A_next)
s.add(A_next)
loop_length = len(A) - i
loop_cnt = (N - i) // loop_length
loop_res = (N - i) % loop_length
ans = sum(A[:i]) + loop_cnt * sum(A[i:]) + sum(A[i: i + loop_res])
# 結果出力
print(ans)
|
p02550
|
n,x,m = list(map(int,input().split()))
#listを2つ使って初項からループ手前までのセット、そして二回目のループのセット。
k_1 = list()
k_2 = list()
#len(k_2)でも良かった
#loop_sumはk_2によって表されるループの和
loop_number = 0
loop_sum = 0
while x not in k_1:
k_1.append(x)
x = x*x%m
while x not in k_2:
k_2.append(x)
loop_number+=1
loop_sum+=x
x = x*x%m
ans = 0
for i in range(len(k_1)):
ans += k_1[i]
ans = ans + loop_sum * ((n-len(k_1))//loop_number)
for i in range((n-len(k_1))%loop_number):
ans += k_2[i]
print(ans)
|
n,x,m = list(map(int,input().split()))
k_1 = set()
k_2 = set()
tmp = list()
loop_number = 0
loop_sum = 0
while x not in k_1:
k_1.add(x)
x = x*x%m
while x not in k_2:
k_2.add(x)
tmp.append(x)
loop_number+=1
loop_sum+=x
x = x*x%m
ans = 0
k_1 = list(k_1)
for i in range(len(k_1)):
ans += k_1[i]
ans = ans + loop_sum * ((n-len(k_1))//loop_number)
for i in range((n-len(k_1))%loop_number):
ans += tmp[i]
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
ans = 0
if x == 0:
print((0))
exit()
elif x == 1:
print(n)
exit()
flag = [False]*m
a = []
while not flag[x]:
flag[x] = True
a.append(x)
x = pow(x, 2, m)
loop_start_idx = a.index(x)
loop_len = len(a) - loop_start_idx
loop_count = (n - loop_start_idx)//loop_len
loop_amari = (n-loop_start_idx)%loop_len
ans = sum(a[:loop_start_idx])
ans += sum(a[loop_start_idx:])*loop_count
ans += sum(a[loop_start_idx: loop_start_idx + loop_amari])
print(ans)
|
n, x, m = list(map(int, input().split()))
flag = [False]*m
a = []
while not flag[x]:
flag[x] = True
a.append(x)
x = pow(x, 2, m)
loop_start_idx = a.index(x)
loop_len = len(a) - loop_start_idx
loop_count = (n - loop_start_idx)//loop_len
loop_amari = (n-loop_start_idx)%loop_len
ans = sum(a[:loop_start_idx])
ans += sum(a[loop_start_idx:])*loop_count
ans += sum(a[loop_start_idx: loop_start_idx + loop_amari])
print(ans)
|
p02550
|
n,x,m=list(map(int,input().split()))
A=[x]
ans=0
for i in range(min(n,m)):
a_i=(A[i]**2)%m
if i ==n-1:
print((sum(A)))
exit()
if a_i==0:
print((sum(A)))
exit()
if a_i in A:
k=A.index(a_i)+1
l=len(A)
roop=A[k-1:l]
many=(n-k+1)//(l-k+1)
ans+=sum(A[:k-1])
ans+=sum(roop)*many
ans+=sum(roop[:(n-k+1)%(l-k+1)])
print(ans)
exit()
A.append(a_i)
|
N, X, M = list(map(int, input().split()))
flag = [False for _ in range(M)]
record = list()
record.append(X)
flag[X] = 1
An = X
for i in range(M + 1):
An = pow(An, 2, M)
if flag[An]:
start = flag[An]
cnt = i + 2 - start
cost = record[-1] - record[start - 2] if start > 1 else record[-1]
break
else:
record.append(An + record[-1])
flag[An] = i + 2
if start >= N:
print((record[N - 1]))
else:
print((((N - start) // cnt) * cost
+ record[(N - start) % cnt + start - 1]))
|
p02550
|
n,x,m= list(map(int, input().strip().split()))
a=[0]*(m)
for i in range(m):
a[i]=i*i%m
a=list(set(a))
t=0
b=[]
b.append(x)
for i in range(m+1):
b.append(b[-1]**2%m)
if len(b)>len(list(set(b))):
break
l=len(b)
for i in range(l-1):
if b[i]==b[l-1]:
q=i
w=l-2-q+1
s=0
for i in range(q):
s+=b[i]
t=0
for i in range(q,l-1):
t+=b[i]
u=(n-q)//w
v=(n-q)%w
ans=0
for i in range(q,q+v):
ans+=b[i]
ans+=s+u*t
print(ans)
|
n,x,m= list(map(int, input().strip().split()))
t=0
b=[]
b.append(x)
for i in range(m+1):
if b[-1]**2%m in b:
b.append(b[-1]**2%m)
break
else:
b.append(b[-1]**2%m)
l=len(b)
for i in range(l-1):
if b[i]==b[l-1]:
q=i
w=l-2-q+1
s=0
for i in range(q):
s+=b[i]
t=0
for i in range(q,l-1):
t+=b[i]
u=(n-q)//w
v=(n-q)%w
ans=0
for i in range(q,q+v):
ans+=b[i]
ans+=s+u*t
print(ans)
|
p02550
|
N, X, M = [int(x) for x in input().split()]
seen = set()
front = []
cycle = []
for i in range(N):
x = pow(X, 2 ** i, M)
if x in seen:
index = front.index(x)
front, cycle = front[:index], front[index:]
break
front.append(x)
seen.add(x)
if N <= len(front):
print((sum(front[:N])))
exit()
if N <= len(front) + len(cycle):
print((sum(front) + sum(cycle[: N - len(front)])))
exit()
q, r = divmod(N - len(front), len(cycle))
if False:
A = [pow(X, 2 ** i, M) for i in range(N)]
B = front + cycle * q + cycle[:r]
print((A, B))
assert A == B
print((sum(front) + sum(cycle) * q + sum(cycle[:r])))
|
def solve(N, X, M):
seen = set()
front = [X]
cycle = []
for i in range(N - 1):
x = (front[-1] * front[-1]) % M
if x in seen: # seen can't be more than M since x is < M
index = front.index(x)
front, cycle = front[:index], front[index:]
break
front.append(x)
seen.add(x)
if N <= len(front):
return sum(front[:N])
if N <= len(front) + len(cycle):
return sum(front) + sum(cycle[: N - len(front)])
q, r = divmod(N - len(front), len(cycle))
if False:
A = [pow(X, 2 ** i, M) for i in range(N)]
B = front + cycle * q + cycle[:r]
print((A, B))
assert A == B
return sum(front) + sum(cycle) * q + sum(cycle[:r])
N, X, M = [int(x) for x in input().split()]
print((solve(N, X, M)))
|
p02550
|
N,X,M = list(map(int,input().split()))
data = [X for i in range(M+1)]
val = set([X])
start = -1
period = -1
for i in range(1,M+1):
data[i] = pow(data[i-1],2,M)
if data[i] in val:
for j in range(0,i):
if data[j]==data[i]:
start = j
period = i-j
break
else:
val.add(data[i])
if N<=M:
print((sum(data[:N])))
else:
res = sum(data[:start])
backet = sum(data[start:start+period])
Q = (N - start) // period
R = (N- start) % period
res += backet*Q + sum(data[start:start+R])
print(res)
|
N,X,M = list(map(int,input().split()))
data = [X for i in range(M+1)]
val = set([X])
start = -1
period = -1
for i in range(1,M+1):
data[i] = pow(data[i-1],2,M)
if data[i] in val:
for j in range(0,i):
if data[j]==data[i]:
start = j
period = i-j
break
break
else:
val.add(data[i])
if N<=M:
print((sum(data[:N])))
else:
res = sum(data[:start])
backet = sum(data[start:start+period])
Q = (N - start) // period
R = (N- start) % period
res += backet*Q + sum(data[start:start+R])
print(res)
|
p02550
|
N,X,M = list(map(int,input().split()))
count = 1
S = X
A = [X]
for i in range(2,N+1):
A_i = (A[-1]*A[-1])%M
A.append(A_i)
S += A_i
if len(A) != len(set(A)):
S -= A_i
del A[-1]
B = A[A.index(A_i):]
S += ((N-len(A))//len(B))*sum(B) + sum(B[:((N-len(A))%len(B))])
break
print(S)
|
N,X,M = list(map(int,input().split()))
S = X
A = [X]
exists = [0]*M
exists[X] = 1
for i in range(2,N+1):
A_i = (A[-1]*A[-1])%M
A.append(A_i)
S += A_i
if exists[A_i] == 0:
exists[A_i] = 1
else:
S -= A_i
del A[-1]
B = A[A.index(A_i):]
S += ((N-len(A))//len(B))*sum(B) + sum(B[:((N-len(A))%len(B))])
break
print(S)
|
p02550
|
n, x, m = [int(_) for _ in input().split()]
d = {}
d_rev = {}
d[x] = 0
d_rev[0] = x
c = 0
while True:
c += 1
x = (x ** 2) % m
if x in d:
roop_idx = d[x]
break
else:
d[x] = c
d_rev[c] = x
# print(d)
# print(d_rev)
ans = 0
if roop_idx >= n:
for i in range(n):
ans += d_rev[i]
print(ans)
else:
for i in range(roop_idx):
ans += d_rev[i]
roop_num = len(d) - roop_idx
roop_sum = 0
for i in range(roop_idx, len(d)):
roop_sum += d_rev[i]
ans += ((n-roop_idx)//roop_num) * roop_sum
roop_last = (n-roop_idx)%roop_num
for i in range(roop_last):
ans += d_rev[roop_idx + i]
print(ans)
|
n, x, m = [int(_) for _ in input().split()]
d = {}
d_rev = {}
d[x] = 0
d_rev[0] = x
c = 0
while True:
c += 1
x = (x ** 2) % m
if x in d:
roop_idx = d[x]
break
else:
d[x] = c
d_rev[c] = x
ans = 0
if roop_idx >= n:
for i in range(n):
ans += d_rev[i]
print(ans)
else:
for i in range(roop_idx):
ans += d_rev[i]
roop_num = len(d) - roop_idx
roop_sum = 0
for i in range(roop_idx, len(d)):
roop_sum += d_rev[i]
ans += ((n-roop_idx)//roop_num) * roop_sum
roop_last = (n-roop_idx)%roop_num
for i in range(roop_last):
ans += d_rev[roop_idx + i]
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
S = set()
A = []
a = x
ans = 0
for i in range(mn):
if a in S: break
S.add(a)
A.append(a)
ans += a
a = a*a%m
if a == 0:
print(ans)
exit()
if len(A) >= mn:
print(ans)
exit()
st_len = 0
while st_len < len(A) and a != A[st_len]: st_len += 1
st = sum(A[:st_len])
cyc_sum = sum(A[st_len:])
cyc_len = len(A) - st_len
cyc_num = (n - st_len) // cyc_len
cyc = cyc_sum * cyc_num
ed_len = (n - st_len) % cyc_len
ed = sum(A[st_len:][:ed_len])
print((st + cyc + ed))
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
S = set()
A = []
a = x
sum_9 = 0 # sum of pre + cycle
for _ in range(mn):
if a in S: break
S.add(a)
A.append(a)
sum_9 += a
a = a*a % m
if a == 0:
print(sum_9)
exit()
if len(A) >= mn:
print(sum_9)
exit()
st_len = A.index(a)
cyc_len = len(A) - st_len
ed_len = (n - st_len) % cyc_len
cyc_num = (n - st_len) // cyc_len
pre = sum(A[:st_len])
cyc = sum_9 - pre
btm = sum(A[st_len: st_len + ed_len])
print((pre + cyc * cyc_num + btm))
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # value of pre & cycle
sum_p = 0 # sum of pre + cycle
X = [False] * m # for cycle check
for _ in range(mn):
if X[x]:
pre_len = P.index(x)
cyc_len = len(P) - pre_len
nxt_len = (n - pre_len) % cyc_len
cyc = sum(P[pre_len:]) * ((n - pre_len) // cyc_len)
remain = sum(P[:pre_len + nxt_len])
print((cyc + remain))
exit()
X[x] = True
P.append(x)
sum_p += x
x = x*x % m
print(sum_p)
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # value of pre & cycle
sum_p = 0 # sum of pre + cycle
X = [False] * m # for cycle check
for _ in range(mn):
if X[x]:
pre_len = P.index(x)
cyc_len = len(P) - pre_len
nxt_len = (n - pre_len) % cyc_len
pre = sum(P[:pre_len])
cyc = (sum_p - pre) * ((n - pre_len) // cyc_len)
nxt = sum(P[pre_len: pre_len + nxt_len])
print((pre + cyc + nxt))
exit()
X[x] = True
P.append(x)
sum_p += x
x = x*x % m
print(sum_p)
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # value of pre & cycle
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
nxt_len = (n - X[x]) % cyc_len
pre = sum(P[:X[x]])
cyc = (sum_p - pre) * ((n - X[x]) // cyc_len)
nxt = sum(P[X[x]: X[x] + nxt_len])
print((pre + cyc + nxt))
exit()
X[x] = i
P.append(x)
sum_p += x
x = x*x % m
print(sum_p)
|
n, x, m = list(map(int, input().split()))
P = [] # value of pre & cycle
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check
for i in range(n):
if X[x] > -1:
cyc_len = len(P) - X[x]
nxt_len = (n - X[x]) % cyc_len
pre = sum(P[:X[x]])
cyc = (sum_p - pre) * ((n - X[x]) // cyc_len)
nxt = sum(P[X[x]: X[x] + nxt_len])
print((pre + cyc + nxt))
exit()
X[x] = i
P.append(x)
sum_p += x
x = x*x % m
print(sum_p)
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # (x,pre_sum)
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
pre = P[X[x]][1]
cyc = (sum_p - pre) * ((n - X[x]) // cyc_len)
nxt = P[X[x] + (n - X[x]) % cyc_len][1] - P[X[x]][1]
print((pre + cyc + nxt))
exit()
P.append([x, sum_p])
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # (x,pre_sum)
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
pre = P[X[x]]
cyc = (sum_p - pre) * ((n - X[x]) // cyc_len)
nxt = P[X[x] + (n - X[x]) % cyc_len] - P[X[x]]
print((pre + cyc + nxt))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # pre_sum
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check & pre_len
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
remain = P[X[x]]
cyc = (sum_p - remain) * ((n - X[x]) // cyc_len)
remain += P[X[x] + (n - X[x]) % cyc_len] - P[X[x]]
print((cyc + remain))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # pre_sum
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check & pre_len
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
cyc = (sum_p - P[X[x]]) * ((n - X[x]) // cyc_len)
remain = P[X[x] + (n - X[x]) % cyc_len]
print((cyc + remain))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
p02550
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # pre_sum
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check & pre_len
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
n -= X[x]
cyc = (sum_p - P[X[x]]) * (n // cyc_len)
remain = P[X[x] + n % cyc_len]
print((cyc + remain))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = [] # pre_sum
sum_p = 0 # sum of pre + cycle
X = [-1] * m # for cycle check & pre_len
for i in range(mn):
if X[x] > -1:
cyc_times, nxt_len = divmod(n-X[x], len(P) - X[x])
cyc = (sum_p - P[X[x]]) * cyc_times
remain = P[X[x] + nxt_len]
print((cyc + remain))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
p02550
|
N, X, M = list(map(int, input().split()))
candicate = [pow(i, 2, M) for i in range(M)]
ans = 0
now = X
A = [0]
X2 = pow(X, 2, M)
d = dict()
flag = True
for i in range(1, N+1):
if i == 1:
A.append(X)
else:
nxt = candicate[A[i-1]]
if d.get(nxt) == None:
if nxt == 0:
A.append(nxt)
break
else:
A.append(nxt)
d[nxt] = i
else:
flag = False
break
if flag:
print((sum(A)))
else:
l = d[nxt]
r = i - 1
circle_total = 0
for j in range(l, r+1):
circle_total += A[j]
for j in range(1, l):
ans += A[j]
width = r - l + 1
N -= (l - 1)
ans += circle_total * (N // width)
for j in range(l, l + N % width):
ans += A[j]
print(ans)
|
N,X,M = list(map(int,input().split()))
ans = X
A = X
TF = True
srt = 1000000
retu = [X]
d = dict()
d[X] = 0
loop = X
flag = False
for i in range(N-1):
if TF:
A = A**2 % M
if d.get(A) != None:
srt = d[A]
goal = i
TF = False
if TF:
retu.append(A)
d[A] = i + 1
loop += A
else:
flag = True
break
if flag:
n = (N-srt)//(goal-srt+1)
saisyo = sum(retu[:srt])
loop -= saisyo
print((saisyo + loop*n + sum(retu[srt:N-n*(goal-srt+1)])))
else:
print((sum(retu[:N])))
|
p02550
|
n,x,m=list(map(int,input().split()))
def f(ai,m):
return (ai*ai)%m
if x==0:
print((0))
elif x==1:
print(n)
elif m==1:
print((0))
elif n<=m*2:
asum=x
ai=x
for i in range(1,n):
ai=f(ai,m)
asum+=ai
print(asum)
else:
aa=[]
ai,icnt,asum=x,0,0
while not ai in aa:
asum+=ai
aa.append(ai)
ai=f(ai,m)
icnt+=1
ai0,icnt0,asum0=x,0,0
if ai!=x:
for i in range(icnt+1):
asum0+=ai0
ai0=f(ai0,m)
icnt0+=1
if ai0==ai:
break
icntk=icnt-icnt0
# print("1:",ai,asum,icnt,ai0,asum0,icnt0)
n0=n-1-icnt0
nk=n0//icntk
nr=n0%icntk
asumk=asum-asum0
air,asumr=ai,0
for i in range(nr):
asumr+=air
air=f(air,m)
asumr+=air
ans=asum0+asumk*nk+asumr
print(ans)
|
n,x,m=list(map(int,input().split()))
def f(ai,m):
return (ai*ai)%m
if x==0:
print((0))
elif x==1:
print(n)
elif m==1:
print((0))
elif n<=m*2:
asum=x
ai=x
for i in range(1,n):
ai=f(ai,m)
asum+=ai
print(asum)
else:
chk=[-1]*m
asum00=[0]*m
ai,asum=x,0
for i in range(m):
if chk[ai]!=-1:
icnt0=chk[ai]
break
else:
chk[ai]=i
asum00[i]=asum
asum+=ai
ai=f(ai,m)
icnt=i
asum0=asum00[icnt0]
icntk=icnt-icnt0
n0=n-1-icnt0
nk=n0//icntk
nr=n0%icntk
asumk=asum-asum0
air,asumr=ai,0
for i in range(nr):
asumr+=air
air=f(air,m)
asumr+=air
ans=asum0+asumk*nk+asumr
print(ans)
|
p02550
|
n,x,m=list(map(int,input().split()))
def f(ai,m):
return (ai*ai)%m
if x==0:
print((0))
elif x==1:
print(n)
elif m==1:
print((0))
elif n<=m*2:
asum=x
ai=x
for i in range(1,n):
ai=f(ai,m)
asum+=ai
print(asum)
else:
chk=[-1]*m
asum00=[0]*m
ai,asum=x,0
for i in range(m):
if chk[ai]!=-1:
icnt0=chk[ai]
break
else:
chk[ai]=i
asum00[i]=asum
asum+=ai
ai=f(ai,m)
icnt=i
asum0=asum00[icnt0]
icntk=icnt-icnt0
n0=n-1-icnt0
nk=n0//icntk
nr=n0%icntk
asumk=asum-asum0
air,asumr=ai,0
for i in range(nr):
asumr+=air
air=f(air,m)
asumr+=air
ans=asum0+asumk*nk+asumr
print(ans)
|
n,x,m=list(map(int,input().split()))
def f(ai,m):
return (ai*ai)%m
if x==0:
print((0))
elif x==1:
print(n)
elif m==1:
print((0))
#elif n<=m*2:
# asum=x
# ai=x
# for i in range(1,n):
# ai=f(ai,m)
# asum+=ai
# print(asum)
else:
chk=[-1]*m
asum00=[0]*m
ai,asum=x,0
for i in range(m):
if chk[ai]!=-1:
icnt0=chk[ai]
break
else:
chk[ai]=i
asum00[i]=asum
asum+=ai
ai=f(ai,m)
icnt=i
asum0=asum00[icnt0]
icntk=icnt-icnt0
n0=n-1-icnt0
nk=n0//icntk
nr=n0%icntk
asumk=asum-asum0
air,asumr=ai,0
for i in range(nr):
asumr+=air
air=f(air,m)
asumr+=air
ans=asum0+asumk*nk+asumr
print(ans)
|
p02550
|
def binary_search(data, value):
left = 0 # 探索する範囲の左端を設定
right = len(data) - 1 # 探索する範囲の右端を設定
while left <= right:
mid = (left + right) // 2 # 探索する範囲の中央を計算
if data[mid] == value:
# 中央の値と一致した場合は位置を返す
return mid
elif data[mid] < value:
# 中央の値より大きい場合は探索範囲の左を変える
left = mid + 1
else:
# 中央の値より小さい場合は探索範囲の右を変える
right = mid - 1
return -1 # 見つからなかった場合
import heapq
n,x,mod = list(map(int,input().split()))
c = []
heapq.heapify(c)
cc = []
sisu = 1
count = 0
while True:
num = pow(x, sisu, mod)
if binary_search(c, num) != -1:
b = cc.index(num)
l = count - b
cycle = cc[b:]
startl = b
start = cc[:b]
break
count += 1
sisu *= 2
heapq.heappush(c, num)
cc.append(num)
# print(cc)
# print(cycle,l)
# print(start,startl)
ans = 0
if n <= startl:
for i in range(n):
ans += start[i]
print(ans)
else:
ans += sum(start)
n -= startl
# print(n)
syo = n // l
amari = n % l
s = [0]*(l+1)
for i in range(1,l+1):
s[i] = s[i-1] + cycle[i-1]
ans += s[l]*syo + s[amari]
print(ans)
|
def binary_search(data, value):
left = 0 # 探索する範囲の左端を設定
right = len(data) - 1 # 探索する範囲の右端を設定
while left <= right:
mid = (left + right) // 2 # 探索する範囲の中央を計算
if data[mid] == value:
# 中央の値と一致した場合は位置を返す
return mid
elif data[mid] < value:
# 中央の値より大きい場合は探索範囲の左を変える
left = mid + 1
else:
# 中央の値より小さい場合は探索範囲の右を変える
right = mid - 1
return -1 # 見つからなかった場合
import heapq
n,x,mod = list(map(int,input().split()))
c = [x]
heapq.heapify(c)
cc = [x]
num = x
count = 1
while True:
num = pow(num, 2, mod)
if binary_search(c, num) != -1:
b = cc.index(num)
l = count - b
cycle = cc[b:]
startl = b
start = cc[:b]
break
count += 1
heapq.heappush(c, num)
cc.append(num)
# print(cc)
# print(cycle,l)
# print(start,startl)
ans = 0
if n <= startl:
for i in range(n):
ans += start[i]
print(ans)
else:
ans += sum(start)
n -= startl
# print(n)
syo = n // l
amari = n % l
s = [0]*(l+1)
for i in range(1,l+1):
s[i] = s[i-1] + cycle[i-1]
ans += s[l]*syo + s[amari]
print(ans)
|
p02550
|
n,x,m=list(map(int, input().split()))
a=x
ans=a
flg=[0]*m
flg[a]=1
l=[a]
lp=-1
for i in range(1,m+1):
if n <= i:
break
tmp=(a*a)%m
a=tmp
if flg[a]==1:
lp = l.index(a)
break
else:
ans+=tmp
l.append(a)
flg[a]=1
if lp != -1:
l2 = l[lp:]
tmp = sum(l2)
b=(n-len(l))//len(l2)
c=n-len(l)-b*len(l2)
ans=ans+(b*tmp)+sum(l2[:c])
print(ans)
|
n,x,m=list(map(int, input().split()))
a=x
ans=a
flg=[0]*m
flg[a]=1
l=[a]
lp=-1
for i in range(1,n):
tmp=(a*a)%m
a=tmp
if flg[a]==1:
lp = l.index(a)
break
else:
ans+=tmp
l.append(a)
flg[a]=1
if lp != -1:
l2 = l[lp:]
tmp = sum(l2)
b=(n-len(l))//len(l2)
c=n-len(l)-b*len(l2)
ans=ans+(b*tmp)+sum(l2[:c])
print(ans)
|
p02550
|
# -*- coding: utf-8 -*-
# map(int, input().split())
N,X,M = list(map(int, input().split()))
first_A = [X]
mod_M = [False for i in range(M)]
is_break = False
for i in range(min(N-1,M+1)):
A_n1 = pow(first_A[-1],2)%M
if A_n1 in first_A+[1,0]:
is_break = True
last_num = A_n1
break
else:
first_A.append(A_n1)
if is_break:
if last_num == 0:
print((sum(first_A)))
elif last_num == 1:
nokori = N-len(first_A)
print((sum(first_A)+nokori))
else: # roop
loop_idx = first_A.index(last_num)
first_A, second_A = first_A[:loop_idx], first_A[loop_idx:]
roop = int((N-len(first_A))/len(second_A))
nokori_kaisuu = (N-len(first_A)) - (roop*len(second_A))
if nokori_kaisuu == 0:
print((sum(first_A)+(sum(second_A)*roop)))
else:
print((sum(first_A)+(sum(second_A)*roop)+sum(second_A[:nokori_kaisuu])))
else:
print((sum(first_A)))
|
# -*- coding: utf-8 -*-
# map(int, input().split())
N,X,M = list(map(int, input().split()))
first_A = [X]
mod_M = [False for i in range(M+1)]
mod_M[0] = True
mod_M[1] = True
is_break = False
for i in range(min(N-1,M+1)):
A_n1 = pow(first_A[-1],2)%M
if mod_M[A_n1]:
is_break = True
last_num = A_n1
break
else:
first_A.append(A_n1)
mod_M[A_n1] = True
if is_break:
if last_num == 0:
print((sum(first_A)))
elif last_num == 1:
nokori = N-len(first_A)
print((sum(first_A)+nokori))
else: # roop
loop_idx = first_A.index(last_num)
first_A, second_A = first_A[:loop_idx], first_A[loop_idx:]
roop = int((N-len(first_A))/len(second_A))
nokori_kaisuu = (N-len(first_A)) - (roop*len(second_A))
if nokori_kaisuu == 0:
print((sum(first_A)+(sum(second_A)*roop)))
else:
print((sum(first_A)+(sum(second_A)*roop)+sum(second_A[:nokori_kaisuu])))
else:
print((sum(first_A)))
|
p02550
|
N,X,M = list(map(int,input().split()))
dps = [X%M]
rt = 0
while True:
d = (dps[-1]**2)%M
if d not in dps:
dps.append(d)
if N == len(dps):
print((sum(dps)))
break
else:
ki = dps.index(d)
RP = (N-ki) // len(dps[ki:])
mod = (N-ki) % len(dps[ki:])
print((sum(dps[:ki]) + RP*sum(dps[ki:])+sum(dps[ki:ki+mod])))
break
|
n, x, m = list(map(int, input().split()))
mn = min(n, m)
P = []
sum_p = 0
X = [-1] * m
for i in range(mn):
if X[x] > -1:
cyc_len = len(P) - X[x]
remain = P[X[x]]
cyc = (sum_p - remain) * ((n - X[x]) // cyc_len)
remain += P[X[x] + (n - X[x]) % cyc_len] - P[X[x]]
print((cyc + remain))
exit()
P.append(sum_p)
sum_p += x
X[x] = i
x = x*x % m
print(sum_p)
|
p02550
|
n, x, m = list(map(int, input().split()))
cnt = [x]
for i in range(m+1):
x = x*x % m
if x in cnt:
break
cnt.append(x)
start = cnt.index(x)
ans = sum(cnt[:start])
roop = len(cnt) - start
#print(roop)
n = n-start
ans = ans + (n//roop)*sum(cnt[start:]) + sum(list(cnt)[start:(start+n%roop)])
print(ans)
|
n, x, m = list(map(int, input().split()))
cnt = [x]
c = set()
c.add(x)
for i in range(m+1):
x = x*x % m
if x in c:
break
cnt.append(x)
c.add(x)
start = cnt.index(x)
ans = sum(cnt[:start])
roop = len(cnt) - start
n = n-start
ans = ans + (n//roop)*sum(cnt[start:]) + sum(list(cnt)[start:(start+n%roop)])
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
a = x
mod = [a]
loop = []
cnt = 0
while cnt < n:
a = a**2 % m
if a in mod:
i = mod.index(a)
before = mod[:i]
loop = mod[i:]
break
mod.append(a)
cnt += 1
length = len(loop)
if length == 0:
print((sum(mod[:n])))
else:
t = (n-i)//length
amari = (n-i) % length
ans = sum(before) + t * sum(loop) + sum(loop[:amari])
print(ans)
|
n, x, m = list(map(int, input().split()))
a = x
dup = [0]*(10**5+10)
mod = [a]
loop = []
cnt = 0
while cnt < n:
a = a**2 % m
if dup[a]==1:
i = mod.index(a)
before = mod[:i]
loop = mod[i:]
break
mod.append(a)
dup[a] = 1
cnt += 1
length = len(loop)
if length == 0:
print((sum(mod[:n])))
else:
t = (n-i)//length
amari = (n-i) % length
ans = sum(before) + t * sum(loop) + sum(loop[:amari])
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
count = 0
# table2jou = []
# for mi in range(m + 1):
# table2jou.append(pow(mi, 2))
# tablef = []
# for mi in range(m + 1):
# # tablef.append(table2jou[mi] % m)
# tablef.append(pow(mi, 2, m))
count = x
pre_an = x
his = [x]
for ni in range(2, n + 1):
# an = tablef[pre_an]
an = pow(pre_an, 2, m)
if an in his:
leftnum = n - ni + 1
start = his.index(an)
end = leftnum % (len(his) - start) + start
loopnum = leftnum // (len(his) - start)
count = count + sum(his[start: end])
count = count + sum(his[start:]) * loopnum
break
his.append(an)
count = count + an
pre_an = an
print(count)
|
n, x, m = list(map(int, input().split()))
count = 0
# table2jou = []
# for mi in range(m + 1):
# table2jou.append(pow(mi, 2))
# tablef = []
# for mi in range(m + 1):
# # tablef.append(table2jou[mi] % m)
# tablef.append(pow(mi, 2, m))
is_used = [0] * (m + 1)
count = x
pre_an = x
his = [x]
for ni in range(2, n + 1):
# an = tablef[pre_an]
an = pow(pre_an, 2, m)
if is_used[an] == 1:
leftnum = n - ni + 1
start = his.index(an)
end = leftnum % (len(his) - start) + start
loopnum = leftnum // (len(his) - start)
count = count + sum(his[start: end])
count = count + sum(his[start:]) * loopnum
break
his.append(an)
is_used[an] = 1
count = count + an
pre_an = an
print(count)
|
p02550
|
def calc_dynamic(n, x, m):
# 結果を保持する辞書
cal_result = {}
# 初期値の設定
cal_result[1] = x
if n == 1:
return x
for i in range(1, n):
cal_result[i+1] = cal_result[i] ** 2 % m
#return cal_result[n]
return sum(cal_result.values())
def calc_dynamic2(n, x, m):
cal_result_0 = 0
cal_result_1 = 0
# 初期値の設定
cal_result_0 = x
total = x
if n == 1:
return x
for i in range(1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
return total
def calc_dynamic3(n, x, m):
# 結果を保持する辞書
cal_result = {}
cal_result_0 = 0
cal_result_1 = 0
loop_range = (0,0)
# 初期値の設定
cal_result_0 = x
total = x
if n == 1:
return x
for i in range(1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
if cal_result_1 in cal_result:
loop_range = (cal_result[cal_result_1], i, cal_result_0, cal_result_1)
break
else:
cal_result[cal_result_1] = (i, total)
if i == n-1:
return total
hoge = i
r = i - loop_range[0][0]
v = total - loop_range[0][1]
hoge += r
while hoge < n:
total += v
hoge += r
cal_result_0 = loop_range[2]
cal_result_1 = loop_range[3]
for i in range(hoge-r+1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
return total
[n, x, m] = [int(x) for x in input().split(" ")]
print((calc_dynamic3(n, x, m)))
|
def calc_dynamic(n, x, m):
# 結果を保持する辞書
cal_result = {}
# 初期値の設定
cal_result[1] = x
if n == 1:
return x
for i in range(1, n):
cal_result[i+1] = cal_result[i] ** 2 % m
#return cal_result[n]
return sum(cal_result.values())
def calc_dynamic2(n, x, m):
cal_result_0 = 0
cal_result_1 = 0
# 初期値の設定
cal_result_0 = x
total = x
if n == 1:
return x
for i in range(1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
return total
def calc_dynamic3(n, x, m):
# 結果を保持する辞書
cal_result = {}
cal_result_0 = 0
cal_result_1 = 0
loop_range = (0,0)
# 初期値の設定
cal_result_0 = x
total = x
if n == 1:
return x
for i in range(1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
if cal_result_1 in cal_result:
loop_range = (cal_result[cal_result_1], i, cal_result_0, cal_result_1)
break
else:
cal_result[cal_result_1] = (i, total)
if i == n-1:
return total
hoge = i
r = i - loop_range[0][0]
v = total - loop_range[0][1]
hoge += r
total += v * ((n - hoge) // r)
hoge += r * ((n - hoge) // r)
#while hoge < n:
# total += v
# hoge += r
cal_result_0 = loop_range[2]
cal_result_1 = loop_range[3]
for i in range(hoge-r+1, n):
cal_result_1 = cal_result_0 * cal_result_0 % m
cal_result_0 = cal_result_1
total += cal_result_1
return total
[n, x, m] = [int(x) for x in input().split(" ")]
print((calc_dynamic3(n, x, m)))
|
p02550
|
n, x, m = list(map(int, input().split()))
mod_list = [-1 for i in range(m)]
value = x
i = 0
head = 0
while i < n:
if value not in mod_list:
mod_list[i] = value
i += 1
value = (value**2)%m
else:
head = mod_list.index(value)
break
if i == n:
print((sum(mod_list[:n])))
else:
block_size = i - head
block_num = (n-head)//block_size
print((sum(mod_list[:head]) + sum(mod_list[head:i])*block_num + sum(mod_list[head:head+(n-head)%block_size])))
|
n, x, m = list(map(int, input().split()))
mod_value = [-1 for i in range(2*m)] #余りの値を頭から格納
mod_check = [False for i in range(m)] #余りが現れたか否か
value = x
i = 0
head = 0
while i < n:
if not mod_check[value]:
mod_value[i] = value
mod_check[value] = True
i += 1
value = (value**2)%m
else:
head = mod_value.index(value)
break
if i == n:
print((sum(mod_value[:n])))
else:
block_size = i - head
block_num = (n-head)//block_size
print((sum(mod_value[:head]) + sum(mod_value[head:i])*block_num + sum(mod_value[head:head+(n-head)%block_size])))
|
p02550
|
from collections import defaultdict
it = lambda: list(map(int, input().strip().split()))
def solve():
N, X, M = it()
if N == 1:
return X % M
value = defaultdict(int)
history = defaultdict(int)
cur = 0
cnt = 0
for i in range(N):
if X in history:
break
value[X] = cur
history[X] = i
cnt += 1
cur += X
X = X * X % M
period = i - history[X]
cur += (N - cnt) // period * (cur - value[X])
for i in range((N - cnt) % period):
cur += X
X = X * X % M
return cur
if __name__ == '__main__':
print((solve()))
|
from collections import defaultdict
it = lambda: list(map(int, input().strip().split()))
def solve():
N, X, M = it()
if N == 1: return X % M
cur = 0
cnt = 0
value = defaultdict(int)
history = defaultdict(int)
for i in range(N):
if X in history: break
value[X] = cur
history[X] = i
cnt += 1
cur += X
X = X * X % M
loop = cur - value[X]
period = i - history[X]
freq, rem = divmod(N - cnt, period)
cur += freq * loop
for i in range(rem):
cur += X
X = X * X % M
return cur
if __name__ == '__main__':
print((solve()))
|
p02550
|
# -*- coding: utf-8 -*-
N, X, M = list(map(int, input().split()))
mod_check_list = [False for _ in range(M)]
mod_list = [(X ** 2) % M]
counter = 1
mod_sum = (X ** 2) % M
last_mod = 0
for i in range(M):
now_mod = (mod_list[-1] ** 2) % M
if mod_check_list[now_mod]:
last_mod = now_mod
break
mod_check_list[now_mod] = True
mod_list.append(now_mod)
counter += 1
mod_sum += now_mod
loop_start_idx = 0
for i in range(counter):
if last_mod == mod_list[i]:
loop_start_idx = i
break
loop_list = mod_list[loop_start_idx:]
loop_num = counter - loop_start_idx
ans = 0
if mod_list[-1] == 0:
ans = X + sum(mod_list[:min(counter, N - 1)])
else:
if (N - 1) <= counter:
ans = X + sum(mod_list[:N - 1])
else:
ans += X + mod_sum
N -= (counter + 1)
ans += sum(loop_list) * (N // loop_num) + sum(loop_list[:N % loop_num])
print(ans)
|
# -*- coding: utf-8 -*-
N, X, M = list(map(int, input().split()))
mod_check_list = [False for _ in range(M)]
mod_list = [(X ** 2) % M]
counter = 1
mod_sum = (X ** 2) % M
last_mod = 0
for i in range(M):
now_mod = (mod_list[-1] ** 2) % M
if mod_check_list[now_mod]:
last_mod = now_mod
break
mod_check_list[now_mod] = True
mod_list.append(now_mod)
counter += 1
mod_sum += now_mod
loop_start_idx = 0
for i in range(counter):
if last_mod == mod_list[i]:
loop_start_idx = i
break
loop_list = mod_list[loop_start_idx:]
loop_num = counter - loop_start_idx
ans = 0
if (N - 1) <= counter:
ans = X + sum(mod_list[:N - 1])
else:
ans += X + mod_sum
N -= (counter + 1)
ans += sum(loop_list) * (N // loop_num) + sum(loop_list[:N % loop_num])
print(ans)
|
p02550
|
N, X, M = list(map(int, input().split()))
A = [X]
a = X
s = X
r = 0
r0 = 0
l = 0
amari = 0
for i in range(M+1):
a = a ** 2 % M
if a in A:
r0 = A.index(a)
l = len(A[r0:])
r = (N - i - 1) // l
amari = (N - i - 1) % l
s = s + sum(A[r0:])*r + sum(A[r0:r0+amari])
break
A.append(a)
s += A[-1]
print(s)
|
N, X, M = list(map(int, input().split()))
A = [X]
A_dict = {X}
a = X
s = X
r = 0
r0 = 0
l = 0
amari = 0
for i in range(M+1):
a = a ** 2 % M
if a in A_dict:
r0 = A.index(a)
l = len(A[r0:])
r = (N - i - 1) // l
amari = (N - i - 1) % l
s = s + sum(A[r0:])*r + sum(A[r0:r0+amari])
break
A.append(a)
A_dict.add(a)
s += A[-1]
print(s)
|
p02550
|
# -*- using utf8 -*-
import sys
inputlinevec = sys.stdin.readline().strip().split(' ')
n = int(inputlinevec[0])
x = int(inputlinevec[1])
m = int(inputlinevec[2])
sum_res = x
crcle_list = list()
crcle_idx = 0
pre_a = x
for idx in range(1, n):
#a范围在0-m之间,不会无限递增,因此很大概率会重复
#a * a % m这种单变量的式子,一旦a出现了之前出现过的值
#后续就会出现重复的序列,然后循环
this_a = (pre_a * pre_a) % m
pre_a = this_a
if this_a not in crcle_list:
crcle_list.append(this_a)
sum_res = sum_res + this_a
else:
crcle_step = len(crcle_list) - crcle_list.index(this_a)
remain_crcle = int((n - idx) / crcle_step)
remain_crcle_tail = int((n - idx) % crcle_step)
crcle_sum = 0
crcle_sum_tail = 0
for a_item in crcle_list[crcle_list.index(this_a):]:
crcle_sum = crcle_sum + a_item
remain_crcle_tail = remain_crcle_tail - 1
if remain_crcle_tail == 0:
crcle_sum_tail = crcle_sum
sum_res = sum_res + (remain_crcle * crcle_sum) + crcle_sum_tail
break
print(sum_res)
|
# -*- using utf8 -*-
import sys
inputlinevec = sys.stdin.readline().strip().split(' ')
n = int(inputlinevec[0])
x = int(inputlinevec[1])
m = int(inputlinevec[2])
sum_res = x
crcle_dict = dict()
crcle_list = list()
crcle_idx = 0
pre_a = x
for idx in range(1, n):
#a范围在0-m之间,不会无限递增,因此很大概率会重复
#a * a % m这种单变量的式子,一旦a出现了之前出现过的值
#后续就会出现重复的序列,然后循环
this_a = (pre_a * pre_a) % m
pre_a = this_a
if this_a not in crcle_dict:
crcle_dict[this_a] = 1
crcle_list.append(this_a)
sum_res = sum_res + this_a
else:
crcle_step = len(crcle_list) - crcle_list.index(this_a)
remain_crcle = int((n - idx) / crcle_step)
remain_crcle_tail = int((n - idx) % crcle_step)
crcle_sum = 0
crcle_sum_tail = 0
for a_item in crcle_list[crcle_list.index(this_a):]:
crcle_sum = crcle_sum + a_item
remain_crcle_tail = remain_crcle_tail - 1
if remain_crcle_tail == 0:
crcle_sum_tail = crcle_sum
sum_res = sum_res + (remain_crcle * crcle_sum) + crcle_sum_tail
break
print(sum_res)
|
p02550
|
N, X, M = list(map(int, input().split()))
if N == 1:
print(X)
exit()
A = [-1] * (10**5 + 1)
A[1] = X
# %M は答えをMOD Mにしなさいといってくれているだけ
# M はたかだか10^5なので10^5繰り返すとどこかで循環する。循環するまで繰り返す。
S = set([X])
i = 2
while True:
A[i] = ((A[i - 1])**2) % M
if A[i] in S:
break
S.add(A[i])
i += 1
# i -= 1
# print(f'{A[:20]=}, {S=}, {i=}')
end_idx = i - 1
start_idx = 0
for start_idx in range(i):
if A[start_idx] == A[i]:
break
num_circles = end_idx - start_idx + 1
# print(f'{start_idx=}, {end_idx=}, {num_circles=}')
A[0] = 0
if start_idx > N:
ans = sum(A[:N + 1])
print(ans)
exit()
# print(f'{A[:20]=}')
# print(f'{A[:start_idx]=}')
v1 = sum(A[:start_idx])
remain_N = N - start_idx + 1
# print(f'{remain_N=}')
div, mod = divmod(remain_N, num_circles)
# print(f'{div=}, {mod=}')
# print(f'{A[start_idx:end_idx + 1]=}')
sum_circles = sum(A[start_idx:end_idx + 1])
# print(f'{sum_circles=}')
v2 = sum_circles * div
if mod == 0:
v3 = 0
else:
# print(f'{A[start_idx:start_idx + mod]=}')
v3 = sum(A[start_idx:start_idx + mod])
ans = v1 + v2 + v3
print(ans)
|
N, X, M = list(map(int, input().split()))
I = [-1] * M
A = []
total = 0
while (I[X] == -1):
A.append(X)
I[X] = len(A)
total += X
X = (X * X) % M
# print(f'{A=}')
# print(f'{I[:20]=}')
# print(f'{total=}')
# print(f'{X=}, {I[X]=}')
c = len(A) - I[X] + 1
s = sum(A[I[X] - 1:])
# print(f'{c=}, {s=}')
ans = 0
if N < len(A):
ans += sum(A[:N])
else:
ans += total
N -= len(A)
ans += s * (N // c)
N %= c
ans += sum(A[I[X] - 1:I[X] - 1 + N])
print(ans)
|
p02550
|
""" E
https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce
def readString():
return sys.stdin.readline()
def readInteger():
return int(readString())
def readStringSet(n):
return sys.stdin.readline().split(" ")[:n]
def readIntegerSet(n):
return list(map(int, readStringSet(n)))
def readIntegerMatrix(n, m):
return reduce(lambda acc, _: acc + [readIntegerSet(m)], list(range(0, n)), [])
def main(N, X, M):
A = X
l = [A]
i = -1
for _ in range(1, M):
A = (A * A) % M if M > 0 else 0
if A in l:
i = l.index(A)
break
else:
l.append(A)
if i == -1:
return sum(l)
else:
s1 = sum(l[:i])
len_repeat = len(l) - i
s2 = sum(l[i:])
return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])
if __name__ == "__main__":
_N, _X, _M = readIntegerSet(3)
print((main(_N, _X, _M)))
|
""" E
https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce
def readString():
return sys.stdin.readline()
def readInteger():
return int(readString())
def readStringSet(n):
return sys.stdin.readline().split(" ")[:n]
def readIntegerSet(n):
return list(map(int, readStringSet(n)))
def readIntegerMatrix(n, m):
return reduce(lambda acc, _: acc + [readIntegerSet(m)], list(range(0, n)), [])
def main(N, X, M):
A = X
m = {A: A}
i = -1
for j in range(1, M):
A = (A * A) % M if M > 0 else 0
if A in m:
i = list(m.keys()).index(A)
break
else:
m[A] = A
if i == -1:
return sum(m.values())
else:
l = list(m.values())
s1 = sum(l[:i])
len_repeat = len(l) - i
s2 = sum(l[i:])
return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])
if __name__ == "__main__":
_N, _X, _M = readIntegerSet(3)
print((main(_N, _X, _M)))
|
p02550
|
import sys
N, X, M = list(map(int, input().split()))
if N == 1:
print(X)
sys.exit()
ans = 0
ans += X - (X%M)
X %= M
def fun(x):
return (x * x) % M
appear_list = [X]
appear_set = {X}
x = X
i_0 = 1
sum_0 = x
while fun(x) not in appear_set:
x = fun(x)
appear_list.append(x)
appear_set.add(x)
sum_0 += x
i_0 += 1
#print(appear_list, x, fun(x))
#print(i_0, N, appear_set)
if i_0 == N:
print((ans + sum_0))
sys.exit()
ans += sum_0
N -= i_0
x = fun(x)
appear_set_2 = {x}
sum_1 = x
sum_list = [0,x]
i_1 = 1
while fun(x) not in appear_set_2:
x = fun(x)
appear_set_2.add(x)
sum_1 += x
sum_list.append(sum_1)
i_1 += 1
sum_0 -= sum_1
i_0 -= i_1
#print(N % i_1)
ans += sum_1 * (N // i_1) + sum_list[(N % i_1)]
print(ans)
|
import sys
N, X, M = list(map(int, input().split()))
if N == 1: #例外
print(X)
sys.exit()
ans = 0
ans += X - (X%M) #XがMより大きい場合、超過分を先に計上する。
X %= M #これで 0 <= X <= M-1 が成り立つようにできた。
def fun(x): #問題の関数を用意(いちいち中身を書いていると面倒くさいため)
return (x * x) % M
appear_set = {X} #すでに現れた数を格納する
i_0 = 1 #今までに調べた個数。現在は「X」の1つだけ。
x = X #このxに何度も関数funを作用させる
sum_0 = x #現在までの和
# ①:すでに出現したことのある数が現れるまで、ループを回す。
# この途中で目標回数Nに到達するなら、その時点で答えを出力する(31-33行目)。
while fun(x) not in appear_set: #次のxが初めて現れる数なら続ける。
x = fun(x) #xにfunを作用
appear_set.add(x) #xを「現れたものリスト」に格納
sum_0 += x #和の更新
i_0 += 1 #調べた個数の更新
if i_0 == N: #目標回数に到達したら、その時点で答えを出力して終了。
print((ans + sum_0))
sys.exit()
# 現在、xには系列に初めて現れた最後の数が入っている。
# 次の数であるfun(x)は、前に現れたことのある数。したがって、ここからループが始まる。
# 整理のため、ここまでの和を計上し、残り回数も減らしておく。
ans += sum_0
N -= i_0
# ②:ループの性質を調べるため、もう一度ループを回したい。
# 欲しいものは3つ。
# 1.ループ1週の和
# 2.ループの途中までの和を記録した配列。
# 3.ループの長さ
# 以下、先ほどと異なる部分を中心に説明する。
x = fun(x) # 次の数へ行く(ループの最初の数)
appear_set_2 = {x}
sum_1 = x # 欲しいもの1。ループ1周の和を記録する。
sum_list = [0,x] # 欲しいもの2。i番目の要素がi番目までの数までの和を示すよう、この後要素を追加する。
i_1 = 1 # すでに調べた個数をカウントする。現在は「x」の1個だけ。
# このi_1が、最終的にループの長さ(欲しいもの3)になる。
# 以下、60行目以外の処理は先ほどと同様。
while fun(x) not in appear_set_2:
x = fun(x)
appear_set_2.add(x)
sum_1 += x
sum_list.append(sum_1) #途中までの和を記録。
i_1 += 1
# ③:上で求めた3つの情報(一周の和sum_1, 途中までの和の記録sum_list, ループ長i_1)
# を使って答えを求める。
ans += sum_1 * (N // i_1) + sum_list[(N % i_1)]
print(ans)
|
p02550
|
N, X, M = list(map(int, input().split()))
ind = 0
l = [X]
while True:
t = l[-1] ** 2 % M
if t not in l:
l.append(t)
else:
ind = l.index(t)
break
S = sum(l[ind:])
L = len(l)
ans = 0
if N <= L:
ans = sum(l[:N])
else:
ans = sum(l)
N -= L
ans += S * (N // (L - ind))
ans += sum(l[ind:ind+(N % (L - ind))])
print(ans)
|
N, X, M = list(map(int, input().split()))
checklist = [True] * 100000
ind = 0
l = [X]
while True:
t = l[-1] ** 2 % M
if checklist[t]:
l.append(t)
checklist[t] = False
else:
ind = l.index(t)
break
S = sum(l[ind:])
L = len(l)
ans = 0
if N <= L:
ans = sum(l[:N])
else:
ans = sum(l)
N -= L
ans += S * (N // (L - ind))
ans += sum(l[ind:ind+(N % (L - ind))])
print(ans)
|
p02550
|
N,X,M=list(map(int,input().split()))
seen=[-2]*M
seen[X]
A=[X]
i=1
while(i<N):
T=A[-1]**2%M
if seen[T]!=-2:
Roop=i-seen[T]
Left,Right=seen[T],i
break
A.append(T)
seen[T]=i
i+=1
if i==N:
print((sum(A)))
exit()
Roopsum=0
for i in range(Left,Right):
Roopsum+=A[i]
Rest=N-len(A)
ans=sum(A)
ans+=Rest//Roop*Roopsum
for i in range(Rest%Roop):
ans+=T
T=T**2%M
print(ans)
|
N,X,M=list(map(int,input().split()))
i=1
A=[X]
seen=[-1]*M
seen[X]=0
while(i<N):
T=A[-1]**2%M
#seen[T]~i-1までがループになっている
if seen[T]!=-1:
Roop=i-seen[T]
Left,Right=seen[T],i
break
seen[T]=i
A.append(T)
i+=1
if i==N:
print((sum(A)))
exit()
ans=sum(A)
RoopSum=0
for i in range(Left,Right):
RoopSum+=A[i]
Rest=N-len(A)
ans+=Rest//Roop*RoopSum
for i in range(Rest%Roop):
ans+=T
T=T**2%M
print(ans)
|
p02550
|
#import sys
#print(sys.maxsize)
N,X,M=list(map(int,input().split()))
#table=list(range(M))
#for i in range(M):
# table[i]=((table[i]%M)**2)%M
#print(table[471])
start=X%M
rireki=list()
rireki.append(start)
ss=0
for j in range(1,N):
start=(start**2)%M
if start in rireki:
ss=rireki.index(start)
break
else:
rireki.append(start)
nn=len(rireki)
rep=(N-ss)//(nn-ss)
nokori=N-ss-rep*(nn-ss)
loop=rireki[ss:]
#print(nn)
#print(rep)
#print(sum(loop))
#print(ss)
#print(nokori+rep*(nn-ss)+ss)
if 0 in rireki:
goukei=sum(rireki)
else:
goukei=rep*sum(loop)+sum(rireki[:ss])+sum(loop[:nokori])
print(goukei)
|
#import sys
#print(sys.maxsize)
N,X,M=list(map(int,input().split()))
#table=list(range(M))
#for i in range(M):
# table[i]=((table[i]%M)**2)%M
#print(table[471])
start=X%M
rset=set()
rireki=list()
rset.add(start)
rireki.append(start)
ss=0
for j in range(1,M+1):
start=(start**2)%M
if start in rset:
ss=rireki.index(start)
break
else:
rireki.append(start)
rset.add(start)
nn=len(rireki)
rep=(N-ss)//(nn-ss)
nokori=N-ss-rep*(nn-ss)
loop=rireki[ss:]
#print(nn)
#print(rep)
#print(sum(loop))
#print(ss)
#print(nokori+rep*(nn-ss)+ss)
if 0 in rireki:
goukei=sum(rireki)
else:
goukei=rep*sum(loop)+sum(rireki[:ss])+sum(loop[:nokori])
print(goukei)
|
p02550
|
N,X,M=list(map(int,input().split()))
table=[X]
ans=X
for i in range(N-1):
nx=table[i]**2
nx%=M
if nx in table:
first=table.index(nx)
oneloop=i+1-first
rest=N-i-1
loops=rest//oneloop
totalofoneloop=sum(table[first:])
ans+=totalofoneloop*loops
remain=rest%oneloop
ans+=sum(table[first:first+remain])
print(ans)
exit()
else:
table.append(nx)
ans+=nx
print(ans)
|
N,X,M=list(map(int,input().split()))
table=[X]
visited=[-1]*M
visited[X]=1
ans=X
for i in range(N-1):
nx=table[i]**2
nx%=M
if visited[nx]>0:
first=table.index(nx)
oneloop=i+1-first
rest=N-i-1
loops=rest//oneloop
totalofoneloop=sum(table[first:])
ans+=totalofoneloop*loops
remain=rest%oneloop
ans+=sum(table[first:first+remain])
print(ans)
exit()
else:
table.append(nx)
visited[nx]=1
ans+=nx
print(ans)
|
p02550
|
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, X, M = list(map(int, readline().split()))
n = 1
P = 1
while n < N:
n *= 2
P += 1
pos = [[0] * M for _ in range(P)]
value = [[0] * M for _ in range(P)]
for r in range(M):
pos[0][r] = r * r % M
value[0][r] = r
for p in range(P - 1):
for r in range(M):
pos[p + 1][r] = pos[p][pos[p][r]]
value[p + 1][r] = value[p][r] + value[p][pos[p][r]]
ans = 0
cur = X % M
for p in range(P):
if N & (1 << p):
ans += value[p][cur]
cur = pos[p][cur]
print(ans)
return
if __name__ == '__main__':
main()
|
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, X, M = list(map(int, readline().split()))
P = N.bit_length()
pos = [[0] * M for _ in range(P)]
value = [[0] * M for _ in range(P)]
for r in range(M):
pos[0][r] = r * r % M
value[0][r] = r
for p in range(P - 1):
for r in range(M):
pos[p + 1][r] = pos[p][pos[p][r]]
value[p + 1][r] = value[p][r] + value[p][pos[p][r]]
ans = 0
cur = X
for p in range(P):
if N & (1 << p):
ans += value[p][cur]
cur = pos[p][cur]
print(ans)
return
if __name__ == '__main__':
main()
|
p02550
|
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, X, M = list(map(int, readline().split()))
P = N.bit_length()
pos = [[0] * M for _ in range(P)]
value = [[0] * M for _ in range(P)]
for r in range(M):
pos[0][r] = r * r % M
value[0][r] = r
for p in range(P - 1):
for r in range(M):
pos[p + 1][r] = pos[p][pos[p][r]]
value[p + 1][r] = value[p][r] + value[p][pos[p][r]]
ans = 0
cur = X
for p in range(P):
if N & (1 << p):
ans += value[p][cur]
cur = pos[p][cur]
print(ans)
return
if __name__ == '__main__':
main()
|
import sys
readline = sys.stdin.readline
def main():
N, X, M = list(map(int, readline().split()))
P = N.bit_length()
pos = [[0] * M for _ in range(P)]
value = [[0] * M for _ in range(P)]
for r in range(M):
pos[0][r] = r * r % M
value[0][r] = r
for p in range(P - 1):
for r in range(M):
pos[p + 1][r] = pos[p][pos[p][r]]
value[p + 1][r] = value[p][r] + value[p][pos[p][r]]
ans = 0
cur = X
for p in range(P):
if N & (1 << p):
ans += value[p][cur]
cur = pos[p][cur]
print(ans)
return
if __name__ == '__main__':
main()
|
p02550
|
n,x,m=list(map(int,input().split()))
ans=x
a=[x]
if n==1:
print(ans)
else:
for i in range(2,n+1):
tmp=a[-1]**2%m
if tmp not in a:
a.append(tmp)
ans+=tmp
else:
t=a.index(tmp)
if len(a)-t>=n-i+1:
ans+=sum(a[t:t+n-i+1])
break
else:
t=a.index(tmp)
tmp_a=(n-i+1)//(len(a)-t)
tmp_b=(n-i+1)-(len(a)-t)*tmp_a
ans+=sum(a[t:])*tmp_a+sum(a[t:t+tmp_b])
break
print(ans)
|
n,x,m=list(map(int,input().split()))
ans=x
a=[x]
d={}
d[x]=1
if n==1:
print(ans)
else:
for i in range(2,n+1):
tmp=a[-1]**2%m
if d.get(tmp,0)==0:
a.append(tmp)
d[tmp]=1
ans+=tmp
else:
t=a.index(tmp)
if len(a)-t>=n-i+1:
ans+=sum(a[t:t+n-i+1])
break
else:
t=a.index(tmp)
tmp_a=(n-i+1)//(len(a)-t)
tmp_b=(n-i+1)-(len(a)-t)*tmp_a
ans+=sum(a[t:])*tmp_a+sum(a[t:t+tmp_b])
break
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
ans = []
flag = False
for i in range(n):
if x in ans:
v = x
flag = True
break
ans.append(x)
x = x**2 % m
if flag:
p = ans.index(v)
l = len(ans) - p
d, e = divmod(n-p, l)
print((sum(ans[:p]) + d*sum(ans[p:]) + sum(ans[p:p+e])))
else:
print((sum(ans)))
|
n, x, m = list(map(int, input().split()))
ans = []
c = [0]*m
flag = False
for i in range(n):
if c[x] == 1:
flag = True
break
ans.append(x)
c[x] = 1
x = x**2 % m
if flag:
p = ans.index(x)
l = len(ans) - p
d, e = divmod(n-p, l)
print((sum(ans[:p]) + d*sum(ans[p:]) + sum(ans[p:p+e])))
else:
print((sum(ans)))
|
p02550
|
n, x, m = list(map(int, input().split()))
l = [x]
loop = []
a = x
for i in range(n - 1):
a = a**2%m
if a not in l:
l.append(a)
else:
if a not in loop:
loop.append(a)
else:
break
if len(loop) > 0:
rest = (n - len(l))%len(loop)
times = (n - len(l))//len(loop)
ans = sum(l) + sum(loop)*times
for i in range(rest):
ans += loop[i]
else:
ans = sum(l)
print(ans)
|
n, x, m = list(map(int, input().split()))
l = [x]
a = x
loopsum = 0
loopnum = 0
for i in range(n - 1):
a = a**2%m
if a not in l:
l.append(a)
else:
pos = l.index(a)
loopnum = len(l[pos:])
loopsum = sum(l[pos:])
break
if loopnum > 0:
rest = (n - len(l))%loopnum
times = (n - len(l))//loopnum
ans = sum(l) + loopsum*times
for i in range(rest):
ans += l[pos + i]
else:
ans = sum(l)
print(ans)
|
p02550
|
n, x, m = list(map(int, input().split()))
a = x
S = [0] * (m + 1)
F = [None] * m
F[x] = 0
i0, j0 = None, None
for i in range(1, m + 1):
S[i] = S[i - 1] + a
a = pow(a, 2, m)
if F[a] is not None:
i0, j0 = F[a], i
F[a] = i
q, r = (n - i0) // (j0 - i0), (n - i0) % (j0 - i0)
print(((S[j0] - S[i0]) * q + S[i0 + r]))
|
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
S.append(S[-1] + x)
if F[x] is not None:
j = F[x]
q, r = (n - j) // (i - j), (n - j) % (i - j)
print(((S[i] - S[j]) * q + S[j + r]))
exit()
F[x] = i
x = pow(x, 2, m)
print((0))
|
p02550
|
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
S.append(S[-1] + x)
if F[x] is not None:
j = F[x]
q, r = (n - j) // (i - j), (n - j) % (i - j)
print(((S[i] - S[j]) * q + S[j + r]))
exit()
F[x] = i
x = pow(x, 2, m)
print((0))
|
n, x, m = list(map(int, input().split()))
S = [0]
F = [None] * m
for i in range(m + 1):
S.append(S[-1] + x)
if F[x] is not None:
j = F[x]
q, r = (n - j) // (i - j), (n - j) % (i - j)
print(((S[i] - S[j]) * q + S[j + r]))
exit()
F[x] = i
x = pow(x, 2, m)
|
p02550
|
import sys
sys.setrecursionlimit(100000000)
while True:
w, h = list(map(int, input().split()))
if not w:
break
n = int(eval(input()))
xlst = [0, w - 1]
ylst = [0, h - 1]
plst = []
for i in range(n):
x1, y1, x2, y2 = list(map(int, input().split()))
plst.append([x1,y1,x2 - 1,y2 - 1])
xlst.append(x1)
# xlst.append(x1 + 1)
xlst.append(x2)
xlst.append(x2 - 1)
ylst.append(y1)
# ylst.append(y1 + 1)
ylst.append(y2)
ylst.append(y2 - 1)
xlst = list(set(xlst))
ylst = list(set(ylst))
sorted_xlst = sorted(xlst)
sorted_ylst = sorted(ylst)
xdic = {}
ydic = {}
for i, v in enumerate(sorted_xlst):
xdic[v] = i
for i, v in enumerate(sorted_ylst):
ydic[v] = i
neww = xdic[sorted_xlst[-1]]
newh = ydic[sorted_ylst[-1]]
# print(neww, newh)
painted = [[0] * (newh) for _ in range(neww)]
def paint_area(x, y):
painted[x][y] = 1
for tx, ty in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
if 0 <= tx <= neww - 1 and 0 <= ty <= newh - 1 and not painted[tx][ty]:
paint_area(tx, ty)
for p in plst:
x1, y1, x2, y2 = p
x1, y1, x2, y2 = xdic[x1], ydic[y1], xdic[x2], ydic[y2]
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
painted[x][y] = 1
# for area in painted:
# print(area)
# print()
ans = 0
for x in range(neww):
for y in range(newh):
if not painted[x][y]:
ans += 1
painted[x][y] = 1
que = [(x, y)]
while que:
px, py = que.pop()
for tx, ty in [(px - 1, py), (px + 1, py), (px, py - 1), (px, py + 1)]:
if 0 <= tx <= neww - 1 and 0 <= ty <= newh - 1 and not painted[tx][ty]:
painted[tx][ty] = 1
que.append((tx,ty))
print(ans)
|
def main():
while True:
w, h = list(map(int, input().split()))
if not w:
break
n = int(eval(input()))
xlst = [0, w - 1]
ylst = [0, h - 1]
plst = []
for i in range(n):
x1, y1, x2, y2 = list(map(int, input().split()))
plst.append([x1,y1,x2 - 1,y2 - 1])
xlst.append(x1)
xlst.append(x2)
xlst.append(x2 - 1)
ylst.append(y1)
ylst.append(y2)
ylst.append(y2 - 1)
xlst = list(set(xlst))
ylst = list(set(ylst))
sorted_xlst = sorted(xlst)
sorted_ylst = sorted(ylst)
xdic = {}
ydic = {}
for i, v in enumerate(sorted_xlst):
xdic[v] = i
for i, v in enumerate(sorted_ylst):
ydic[v] = i
neww = xdic[sorted_xlst[-1]]
newh = ydic[sorted_ylst[-1]]
painted = [[1] * (newh + 2)]
for _ in range(neww):
painted.append([1] + [0] * newh + [1])
painted.append([1] * (newh + 2))
for p in plst:
x1, y1, x2, y2 = p
x1, y1, x2, y2 = xdic[x1] + 1, ydic[y1] + 1, xdic[x2] + 1, ydic[y2] + 1
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
painted[x][y] = 1
ans = 0
que = []
app = que.append
pp = que.pop
for x in range(1, neww + 1):
for y in range(1, newh + 1):
if not painted[x][y]:
ans += 1
painted[x][y] = 1
app((x,y))
while que:
px, py = pp()
for tx, ty in [(px - 1, py), (px + 1, py), (px, py - 1), (px, py + 1)]:
if not painted[tx][ty]:
painted[tx][ty] = 1
app((tx,ty))
print(ans)
main()
|
p00454
|
def main():
while True:
w, h = list(map(int, input().split()))
if not w:
break
n = int(eval(input()))
xlst = [0, w - 1]
ylst = [0, h - 1]
plst = []
for i in range(n):
x1, y1, x2, y2 = list(map(int, input().split()))
plst.append([x1,y1,x2 - 1,y2 - 1])
xlst.append(x1)
xlst.append(x2)
xlst.append(x2 - 1)
ylst.append(y1)
ylst.append(y2)
ylst.append(y2 - 1)
xlst = list(set(xlst))
ylst = list(set(ylst))
sorted_xlst = sorted(xlst)
sorted_ylst = sorted(ylst)
xdic = {}
ydic = {}
for i, v in enumerate(sorted_xlst):
xdic[v] = i
for i, v in enumerate(sorted_ylst):
ydic[v] = i
neww = xdic[sorted_xlst[-1]]
newh = ydic[sorted_ylst[-1]]
painted = [[1] * (newh + 2)]
for _ in range(neww):
painted.append([1] + [0] * newh + [1])
painted.append([1] * (newh + 2))
for p in plst:
x1, y1, x2, y2 = p
x1, y1, x2, y2 = xdic[x1] + 1, ydic[y1] + 1, xdic[x2] + 1, ydic[y2] + 1
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
painted[x][y] = 1
ans = 0
que = []
app = que.append
pp = que.pop
for x in range(1, neww + 1):
for y in range(1, newh + 1):
if not painted[x][y]:
ans += 1
painted[x][y] = 1
app((x,y))
while que:
px, py = pp()
for tx, ty in [(px - 1, py), (px + 1, py), (px, py - 1), (px, py + 1)]:
if not painted[tx][ty]:
painted[tx][ty] = 1
app((tx,ty))
print(ans)
main()
|
def main():
while True:
w, h = list(map(int, input().split()))
if not w:
break
n = int(eval(input()))
xlst = [0, w - 1]
ylst = [0, h - 1]
plst = []
for i in range(n):
x1, y1, x2, y2 = list(map(int, input().split()))
plst.append([x1,y1,x2 - 1,y2 - 1])
xlst.append(x1)
xlst.append(x2)
xlst.append(x2 - 1)
ylst.append(y1)
ylst.append(y2)
ylst.append(y2 - 1)
xlst = list(set(xlst))
ylst = list(set(ylst))
xlst.sort()
ylst.sort()
xdic = {}
ydic = {}
for i, v in enumerate(xlst):
xdic[v] = i
for i, v in enumerate(ylst):
ydic[v] = i
neww = xdic[xlst[-1]]
newh = ydic[ylst[-1]]
painted = [[1] * (newh + 2)]
for _ in range(neww):
painted.append([1] + [0] * newh + [1])
painted.append([1] * (newh + 2))
for p in plst:
x1, y1, x2, y2 = p
x1, y1, x2, y2 = xdic[x1] + 1, ydic[y1] + 1, xdic[x2] + 1, ydic[y2] + 1
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
painted[x][y] = 1
stack = []
app = stack.append
pp = stack.pop
direct = ((-1, 0), (1, 0), (0, -1), (0, 1))
ans = 0
for x in range(1, neww + 1):
for y in range(1, newh + 1):
if not painted[x][y]:
ans += 1
painted[x][y] = 1
app((x,y))
while stack:
px, py = pp()
for dx, dy in direct:
tx, ty = px + dx, py + dy
if not painted[tx][ty]:
painted[tx][ty] = 1
app((tx,ty))
print(ans)
main()
|
p00454
|
# tree diameter if (currDia <= k) true else shorten() while (dia >= k) O(n) dia readjust
# multiple pairs . centroid of tree --> on largest path find centroid --> maintain a heap ?
from queue import Queue
def main():
n, d = list(map(int, input().split()))
adj = [[] for i in range(n)]
edges = []
for i in range(n-1):
a, b = list(map(int, input().split()))
adj[a-1].append(b-1)
adj[b-1].append(a-1)
edges.append((a-1, b-1))
ans = 1000000
if (d % 2 == 0):
for i in range(n):
ans = min(ans, compute(adj, i, d))
else:
for i in range(n-1):
ans = min(ans, computeEdges(adj, edges[i], d-1))
print(ans)
def compute(adj, u, dia):
vis = [False]*len(adj)
dis = [0]*len(adj)
q = Queue(maxsize = len(adj))
q.put(u)
vis[u] = True
while (q.qsize() > 0):
elem = q.get()
for v in adj[elem]:
if (vis[v] == False):
q.put(v)
vis[v] = True
dis[v] = dis[elem] + 1
count = 0
for a in dis:
if (a > dia/2):
count += 1
return count
def computeEdges(adj, edge, dia):
vis = [False]*len(adj)
dis = [0]*len(adj)
q = Queue(maxsize = len(adj))
q.put(edge[0])
q.put(edge[1])
vis[edge[0]] = True
vis[edge[1]] = True
while (q.qsize() > 0):
elem = q.get()
for v in adj[elem]:
if (vis[v] == False):
q.put(v)
vis[v] = True
dis[v] = dis[elem] + 1
count = 0
for a in dis:
if (a > dia/2):
count += 1
return count
main()
|
# tree diameter if (currDia <= k) true else shorten() while (dia >= k) O(n) dia readjust
# multiple pairs . centroid of tree --> on largest path find centroid --> maintain a heap ?
from collections import deque
def main():
n, d = list(map(int, input().split()))
adj = [[] for i in range(n)]
edges = []
for i in range(n-1):
a, b = list(map(int, input().split()))
adj[a-1].append(b-1)
adj[b-1].append(a-1)
edges.append((a-1, b-1))
ans = 1000000
if (d % 2 == 0):
for i in range(n):
ans = min(ans, compute(adj, i, d))
else:
for i in range(n-1):
ans = min(ans, computeEdges(adj, edges[i], d-1))
print(ans)
def compute(adj, u, dia):
vis = [False]*len(adj)
dis = [0]*len(adj)
q = deque()
q.append(u)
vis[u] = True
while (len(q) > 0):
elem = q.popleft()
for v in adj[elem]:
if (vis[v] == False):
q.append(v)
vis[v] = True
dis[v] = dis[elem] + 1
count = 0
for a in dis:
if (a > dia/2):
count += 1
return count
def computeEdges(adj, edge, dia):
vis = [False]*len(adj)
dis = [0]*len(adj)
q = deque()
q.append(edge[0])
q.append(edge[1])
vis[edge[0]] = True
vis[edge[1]] = True
while (len(q) > 0):
elem = q.popleft()
for v in adj[elem]:
if (vis[v] == False):
q.append(v)
vis[v] = True
dis[v] = dis[elem] + 1
count = 0
for a in dis:
if (a > dia/2):
count += 1
return count
main()
|
p04049
|
from collections import deque
N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
T[a].append(b)
T[b].append(a)
E.append((a, b))
def dfs(n):
visited = [False] * N
stack = [[n, 0]]
longest = [-1, -1]
while stack:
node, weight = stack.pop()
if visited[node]:
continue
visited[node] = True
if longest[1] < weight:
longest = [node, weight]
for n in T[node]:
if not visited[n]:
stack.append([n, weight + 1])
return longest
def bfs(n):
visited = [False] * N
dist = [0] * N
queue = deque([n])
while queue:
node = queue.pop()
if visited[node]:
continue
visited[node] = True
for n in T[node]:
if not visited[n]:
dist[n] = dist[node] + 1
queue.appendleft(n)
return dist
xn, xw = dfs(0)
yn, yw = dfs(xn)
diameter = yw
d = bfs(0)
ans = float('inf')
if K % 2 == 0:
# 全ての頂点について全探索
for i in range(N):
dist = bfs(i)
ans = min(ans, len(list([x for x in dist if K / 2 < x])))
else:
# 全ての辺について全探索
for a, b in E:
dist1 = bfs(a)
dist2 = bfs(b)
dist = [min(d1, d2) for d1, d2 in zip(dist1, dist2)]
ans = min(ans, len(list([x for x in dist if (K-1) / 2 < x])))
print(ans)
|
from collections import deque
N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
T[a].append(b)
T[b].append(a)
E.append((a, b))
def bfs(n):
visited = [False] * N
dist = [0] * N
queue = deque([n])
while queue:
node = queue.pop()
if visited[node]:
continue
visited[node] = True
for n in T[node]:
if not visited[n]:
dist[n] = dist[node] + 1
queue.appendleft(n)
return dist
dist = []
for i in range(N):
dist.append(bfs(i))
ans = float('inf')
if K % 2 == 0:
# 全ての頂点について全探索
for i in range(N):
ans = min(ans, len(list([x for x in dist[i] if K / 2 < x])))
else:
# 全ての辺について全探索
for a, b in E:
adist = [min(d1, d2) for d1, d2 in zip(dist[a], dist[b])]
ans = min(ans, len(list([x for x in adist if (K-1) / 2 < x])))
print(ans)
|
p04049
|
from collections import deque
N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
T[a].append(b)
T[b].append(a)
E.append((a, b))
def bfs(n):
visited = [False] * N
dist = [0] * N
queue = deque([n])
while queue:
node = queue.pop()
if visited[node]:
continue
visited[node] = True
for n in T[node]:
if not visited[n]:
dist[n] = dist[node] + 1
queue.appendleft(n)
return dist
dist = []
for i in range(N):
dist.append(bfs(i))
ans = float('inf')
if K % 2 == 0:
# 全ての頂点について全探索
for i in range(N):
ans = min(ans, len([d for d in dist[i] if d > K / 2]))
else:
# 全ての辺について全探索
for a, b in E:
adist = [(1 if min(d1, d2) > (K-1) / 2 else 0) for d1, d2 in zip(dist[a], dist[b])]
ans = min(ans, sum(adist))
print(ans)
|
from collections import deque
N, K = list(map(int, input().split()))
T = [[] for i in range(N)]
E = []
for i in range(N-1):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
T[a].append(b)
T[b].append(a)
E.append([a, b])
def bfs(n):
visited = [False] * N
dist = [0] * N
queue = deque([n])
while queue:
node = queue.pop()
if visited[node]:
continue
visited[node] = True
for n in T[node]:
if not visited[n]:
dist[n] = dist[node] + 1
queue.appendleft(n)
return dist
dist = []
for i in range(N):
dist.append(bfs(i))
ans = float('inf')
if K % 2 == 0:
for i in range(N):
ans = min(ans, len([d for d in dist[i] if d > K / 2]))
else:
for a, b in E:
ans = min(ans, len([d for d in [min(d1, d2) for d1, d2 in zip(dist[a], dist[b])] if d > (K-1) / 2]))
print(ans)
|
p04049
|
o=lambda:list(map(int,input().split()))
T,F=True,False
n,k=o()
e=[[] for _ in [0]*n]
for _ in [0]*(n-1):a,b=o();e[a-1]+=[b-1];e[b-1]+=[a-1]
a=10**5
def dfs(x,f):
if f>=0:l[f]=T
q=[(x,0)]
while len(q):
v,c=q.pop(0)
if c>k/2:break
l[v]=T
for w in e[v]:
if ~l[w]:q+=[(w,c+1)]
return n-l.count(T)
if k%2:
for i in range(n):
for j in e[i]:
if i<j:l=[F]*n;dfs(i,j);a=min(a,dfs(j,i))
else:
for i in range(n):l=[F]*n;a=min(a,dfs(i,-1))
print(a)
|
o=lambda:list(map(int,input().split()))
T,F=True,False
n,k=o()
e=[[] for _ in [0]*n]
for _ in [0]*(n-1):a,b=o();e[a-1]+=[b-1];e[b-1]+=[a-1]
a=10**5
def dfs(x,f):
if f>=0:l[f]=T
q=[(x,0)]
while len(q):
v,c=q.pop(0)
if c>k/2:break
l[v]=T
for w in e[v]:
if not l[w]:q+=[(w,c+1)]
return n-l.count(T)
if k%2:
for i in range(n):
for j in e[i]:
if i<j:l=[F]*n;dfs(i,j);a=min(a,dfs(j,i))
else:
for i in range(n):l=[F]*n;a=min(a,dfs(i,-1))
print(a)
|
p04049
|
import sys
input = sys.stdin.readline
n,k = list(map(int,input().split()))
edge = [[] for i in range(n)]
alledge = []
for i in range(n-1):
a,b = list(map(int,input().split()))
edge[a-1].append(b-1)
edge[b-1].append(a-1)
alledge.append((a-1,b-1))
def f(x,y,c):
global tmp
c += 1
for e in edge[x]:
if e == y:
continue
if c > d:
tmp +=1
f(e,x,c)
sys.setrecursionlimit(4100000)
if k % 2 == 0:
d = k//2
ass = 2001
for i in range(n):
tmp = 0
f(i,-1,0)
ass = min(ass,tmp)
print(ass)
else:
d = (k-1)//2
ass = 2001
for e1 in alledge:
tmp = 0
f(e1[0],e1[1],0)
f(e1[1],e1[0],0)
ass = min(ass,tmp)
print(ass)
|
import sys
#input = sys.stdin.readline
n,k = list(map(int,input().split()))
edge = [[] for i in range(n)]
alledge = []
for i in range(n-1):
a,b = list(map(int,input().split()))
edge[a-1].append(b-1)
edge[b-1].append(a-1)
alledge.append((a-1,b-1))
def f(x,y,c):
global tmp
c += 1
for e in edge[x]:
if e == y:
continue
if c > d:
tmp +=1
f(e,x,c)
sys.setrecursionlimit(4100000)
if k % 2 == 0:
d = k//2
ass = 2001
for i in range(n):
tmp = 0
f(i,-1,0)
ass = min(ass,tmp)
print(ass)
else:
d = (k-1)//2
ass = 2001
for e1 in alledge:
tmp = 0
f(e1[0],e1[1],0)
f(e1[1],e1[0],0)
ass = min(ass,tmp)
print(ass)
|
p04049
|
N,K=list(map(int,input().split()))
G=[[] for i in range(N)]
a=[0 for i in range(N-1)]
b=[0 for i in range(N-1)]
for i in range(N-1):
a[i],b[i]=list(map(int,input().split()))
a[i]-=1;b[i]-=1
G[a[i]].append(b[i])
G[b[i]].append(a[i])
P=[-1 for i in range(N)]
rnk=[-1 for i in range(N)]
q=[0]
rnk[0]=0
while(len(q)>0):
r=q[-1];q.pop()
for p in G[r]:
if rnk[p]!=-1:
continue
rnk[p]=rnk[r]+1
P[p]=r
q.append(p)
S=[[] for i in range(N)]
for i in range(N):
S[i].append(P[i])
while(True):
tmp=[0 for i in range(N)]
flag=0
for i in range(N):
if S[i][-1]==-1:
tmp[i]=-1
else:
flag=1
tmp[i]=S[S[i][-1]][-1]
if flag==0:
break
for i in range(N):
S[i].append(tmp[i])
#pのk個上(存在しない場合は-1)
def bef(p,k):
if rnk[p]<k:
return -1
else:
m=str(bin(k))[2:][::-1]
n=len(m)
res=p
for i in range(n):
if m[i]=="1":
res=S[res][i]
return res
M=len(S[0])
def dist(x,y):
if rnk[x]>rnk[y]:
return (rnk[x]-rnk[y])+dist(bef(x,rnk[x]-rnk[y]),y)
elif rnk[x]<rnk[y]:
return (rnk[y]-rnk[x])+dist(x,bef(y,rnk[y]-rnk[x]))
else:
if x==y:
return 0
res=0
tmpx=x
tmpy=y
while(True):
j=0
if tmpx==tmpy:
return res
for i in range(M-1):
if S[tmpx][i]!=S[tmpy][i] and S[tmpx][i+1]==S[tmpy][i+1]:
j=i
break
res+=2**(j+1)
tmpx=S[tmpx][i]
tmpy=S[tmpy][i]
'''
X=max(rnk)
leaf=[]
for i in range(N):
if rnk[i]==X:
leaf.append(i)
'''
d=[[dist(i,j) for i in range(N)] for j in range(N)]
#dia=max([max([d[i][j] for i in range(N)]) for j in range(N)])
if K%2==0:
t=[[d[i][j] for i in range(N)] for j in range(N)]
D=K//2
ans=[0 for i in range(N)]
for i in range(N):
for j in range(N):
if t[i][j]>D:
ans[i]+=1
print((min(ans)))
else:
t=[[min([d[a[i]][j],d[b[i]][j]]) for j in range(N)] for i in range(N-1)]
ans=[0 for i in range(N-1)]
D=(K-1)//2
for i in range(N-1):
for j in range(N):
if t[i][j]>D:
ans[i]+=1
print((min(ans)))
|
N,K=list(map(int,input().split()))
G=[[] for i in range(N)]
a=[0 for i in range(N-1)]
b=[0 for i in range(N-1)]
for i in range(N-1):
a[i],b[i]=list(map(int,input().split()))
a[i]-=1;b[i]-=1
G[a[i]].append(b[i])
G[b[i]].append(a[i])
d=[[-1 for i in range(N)] for j in range(N)]
for i in range(N):
q=[i]
d[i][i]=0
while(len(q)>0):
r=q[-1];q.pop()
for p in G[r]:
if d[i][p]!=-1:
continue
d[i][p]=d[i][r]+1
q.append(p)
#dia=max([max([d[i][j] for i in range(N)]) for j in range(N)])
if K%2==0:
t=[[d[i][j] for i in range(N)] for j in range(N)]
D=K//2
ans=[0 for i in range(N)]
for i in range(N):
for j in range(N):
if t[i][j]>D:
ans[i]+=1
print((min(ans)))
else:
t=[[min([d[a[i]][j],d[b[i]][j]]) for j in range(N)] for i in range(N-1)]
ans=[0 for i in range(N-1)]
D=(K-1)//2
for i in range(N-1):
for j in range(N):
if t[i][j]>D:
ans[i]+=1
print((min(ans)))
|
p04049
|
import sys
stdin = sys.stdin
def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
from collections import deque
def bfs(graph:list, start:int) -> list:
# 未探索のノードは距離null
node = len(graph)
dist = [None]*node
# 始点ノードの距離を0とし、bfsのためのqueueを作成
dist[start] = 0
que = deque([(0,start)])
# 未探索のノードをqueueに入れる
# kより大きいの距離のものを数える
while que:
cost, cur_node = que.popleft()
for nex_cost, nex_node in graph[cur_node]:
if dist[nex_node] is not None:
continue
else:
dist[nex_node] = dist[cur_node] + nex_cost
que.append((dist[nex_node], nex_node))
return dist
# 入力, グラフ作成
n,k = li()
adj_list = [[] for _ in range(n)]
edges = []
for _ in range(n-1):
a,b = li_()
adj_list[a].append((1,b))
adj_list[b].append((1,a))
edges.append((a,b))
ans = n
# kが奇数の時
if k%2:
for a,b in edges:
dist1 = bfs(adj_list, a)
dist2 = bfs(adj_list, b)
ans = min(ans, sum([min(d1,d2) > (k-1)//2 for d1,d2 in zip(dist1, dist2)]))
# kが偶数の時
else:
for st in range(n):
dist = bfs(adj_list, st)
ans = min(ans, sum([d > k//2 for d in dist]))
print(ans)
|
import sys
stdin = sys.stdin
def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
from collections import deque
from collections import defaultdict
def bfs(graph:list, start:int) -> list:
# 未探索のノードは距離null
node = len(graph)
dist = [None]*node
# 始点ノードの距離を0とし、bfsのためのqueueを作成
dist[start] = 0
que = deque([(0,start)])
# 未探索のノードをqueueに入れる
# kより大きいの距離のものを数える
while que:
cost, cur_node = que.popleft()
for nex_cost, nex_node in graph[cur_node]:
if dist[nex_node] is not None:
continue
else:
dist[nex_node] = dist[cur_node] + nex_cost
que.append((dist[nex_node], nex_node))
return dist
# 入力, グラフ作成
n,k = li()
adj_list = [[] for _ in range(n)]
edges = []
for _ in range(n-1):
a,b = li_()
adj_list[a].append((1,b))
adj_list[b].append((1,a))
edges.append((a,b))
ans = n
# kが奇数の時
if k%2:
for a,b in edges:
dist1 = bfs(adj_list, a)
dist2 = bfs(adj_list, b)
ans = min(ans, sum([min(d1,d2) > (k-1)//2 for d1,d2 in zip(dist1, dist2)]))
# kが偶数の時
else:
for st in range(n):
dist = bfs(adj_list, st)
ans = min(ans, sum([d > k//2 for d in dist]))
print(ans)
|
p04049
|
from collections import deque
def rad_reach(bfr,h,rest,E):
cnt = 0
Q = deque([(bfr,h,rest)])
while Q:
cnt += 1
bfr,h,rest = Q.popleft()
if rest > 0:
for nxt in E[h]:
if nxt == bfr:
continue
Q.append((h,nxt,rest-1))
return cnt
def solve():
N,K = list(map(int,input().split()))
pairs = []
E = [[] for i in range(N)]
for i in range(N-1):
p = [int(x)-1 for x in input().split()]
pairs.append(p)
E[p[0]].append(p[1])
E[p[1]].append(p[0])
ans = N
rad = K/2
if K % 2 == 0:
for c in range(N):
ans = min(ans,N-rad_reach(-1,c,rad,E))
else:
for c1,c2 in pairs:
ans = min(ans,N-rad_reach(c2,c1,rad,E)-rad_reach(c1,c2,rad,E))
print(ans)
solve()
|
from sys import setrecursionlimit
setrecursionlimit(100000)
def rad_reach(b,h,dist,E,rad):
cnt = 1
if dist < rad:
for nxt in E[h]:
if nxt == b:
continue
cnt += rad_reach(h,nxt,dist+1,E,rad)
return cnt
def solve():
N,K = list(map(int,input().split()))
pairs = []
E = [[] for i in range(N)]
for i in range(N-1):
a,b = [int(x)-1 for x in input().split()]
E[a].append(b)
E[b].append(a)
pairs.append((a,b))
ans = N
rad = K/2
if K % 2 == 0:
for c in range(N):
ans = min(ans,N-rad_reach(-1,c,0,E,rad))
else:
for c1,c2 in pairs:
ans = min(ans,N-rad_reach(c2,c1,0,E,rad)-rad_reach(c1,c2,0,E,rad))
print(ans)
solve()
|
p04049
|
from collections import deque
n,k = (int(i) for i in input().split())
b = [[int(i)-1 for i in input().split()] for i in range(n-1)]
x,d,ans,c = [[] for i in range(n)],[[] for i in range(n)],n,0
for i,j in b:
x[i].append(j)
x[j].append(i)
for i in x: c = max(len(i),c)
if n-c+1<=k: ans = 0
elif k==1: ans = n-2
else:
for i in range(n):
q,v = deque(),[1]*n
v[i] = 0
for j in x[i]:
q.append((j,1,j))
d[i].append(j)
v[j] = 0
while q:
p = q.pop()
if p[1]<k//2:
for j in x[p[0]]:
if v[j]:
q.append((j,p[1]+1,p[2]))
d[i].append(p[2])
v[j] = 0
if k%2:
for i,j in b: ans = min(ans,n-len(d[i])-len(d[j])+d[i].count(j)+d[j].count(i)-2)
else:
for i in range(n): ans = min(ans,n-len(d[i])-1)
print(ans)
|
from collections import deque
n,k = (int(i) for i in input().split())
b = [[int(i)-1 for i in input().split()] for i in range(n-1)]
x,d,ans,c = [[] for i in range(n)],[[] for i in range(n)],n,0
for i,j in b:
x[i].append(j)
x[j].append(i)
def f(s):
for i in range(n):
q,v = deque(),[1]*n
v[i] = 0
for j in x[i]:
q.append((j,1,j))
d[i].append(j)
v[j] = 0
while q:
p = q.pop()
if p[1]<s:
for j in x[p[0]]:
if v[j]:
q.append((j,p[1]+1,p[2]))
d[i].append(p[2])
v[j] = 0
if k>n//2:
for i in x: c = max(len(i),c)
if n-c+1<=k: ans = 0
elif k==1: ans = n-2
else:
f(k//2)
if k%2:
for i,j in b: ans = min(ans,n-len(d[i])-len(d[j])+d[i].count(j)+d[j].count(i)-2)
else:
for i in range(n): ans = min(ans,n-len(d[i])-1)
print(ans)
|
p04049
|
def main():
n, k = list(map(int, input().split()))
a = []
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = list(map(int, input().split()))
u -= 1
v -= 1
a.append((u, v))
g[u].append(v)
g[v].append(u)
st = []
pu = st.append
po = st.pop
ans = 0
if k % 2:
k = k / 2 + 1
for u, v in a:
c = 0
pu((u, k, v))
pu((v, k, u))
while st:
u, d, p = po()
d -= 1
c += 1
if d:
for v in g[u]:
if v != p:
pu((v, d, u))
if ans < c:
ans = c
else:
k = k / 2 + 1
for i in range(n):
c = 0
pu((i, k, -1))
while c < len(st):
u, d, p = st[c]
d -= 1
if d:
for v in g[u]:
if v != p:
pu((v, d, u))
c += 1
if ans < c:
ans = c
del st[:]
print(n - ans)
main()
|
def main(le=len):
n, k = list(map(int, input().split()))
a = []
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = list(map(int, input().split()))
u -= 1
v -= 1
a.append((u, v))
g[u].append(v)
g[v].append(u)
st = []
pu = st.append
po = st.pop
ans = 0
if k % 2:
k = k / 2 + 1
for u, v in a:
c = 0
pu((u, k, v))
pu((v, k, u))
while c < le(st):
u, d, p = st[c]
d -= 1
if d:
for v in g[u]:
if v != p:
pu((v, d, u))
c += 1
if ans < c:
ans = c
del st[:]
else:
k = k / 2 + 1
for i in range(n):
c = 0
pu((i, k, -1))
while c < le(st):
u, d, p = st[c]
d -= 1
if d:
for v in g[u]:
if v != p:
pu((v, d, u))
c += 1
if ans < c:
ans = c
del st[:]
print(n - ans)
main()
|
p04049
|
import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
H = [0]+list(map(int, input().split()))
dp = [[[10**18]*(N+1) for _ in range(K+1)] for _ in range(2)]
dp[0][0][0] = 0
for i in range(N):
for j in range(K+1):
for k in range(N+1):
dp[(i+1)%2][j][k] = 10**18
for j in range(K+1):
for k in range(N+1):
if j+1<=K:
dp[(i+1)%2][j+1][k] = min(dp[(i+1)%2][j+1][k], dp[i%2][j][k])
dp[(i+1)%2][j][i+1] = min(dp[(i+1)%2][j][i+1], dp[i%2][j][k]+max(0, H[i+1]-H[k]))
ans = 10**18
for i in range(K+1):
for j in range(N+1):
ans = min(ans, dp[N%2][i][j])
print(ans)
|
import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
H = [0]+list(map(int, input().split()))
dp = [[10**18]*(N+1) for _ in range(N-K+1)]
dp[0][0] = 0
for i in range(N-K):
for j in range(N+1):
for k in range(j):
dp[i+1][j] = min(dp[i+1][j], dp[i][k]+max(0, H[j]-H[k]))
print((min(dp[N-K])))
|
p02864
|
n,K=list(map(int,input().split()))
l=list(map(int,input().split()))
INF=float('inf')
dp=[[[] for j in range(K+1)] for i in range(n+1)]
dp[0][0]=[(0,0)]
for i,j in enumerate(l,1):
a1,b1=dp[i-1][0][0]
dp[i][0]=[(a1+max(0,j-b1),j)]
for i,j in enumerate(l,1):
for k in range(1,min(K+1,i+1)):
tl=[]
for a1,b1 in dp[i-1][k]:
tl.append((a1+max(0,j-b1),j))
dp[i][k]=tl+dp[i-1][k-1]
a=dp[-1][-1]
a.sort()
print((a[0][0]))
|
n,K=list(map(int,input().split()))
l=list(map(int,input().split()))
INF=float('inf')
dp=[[[] for j in range(K+1)] for i in range(n+1)]
dp[0][0]=[(0,0)]
for i,j in enumerate(l,1):
a1,b1=dp[i-1][0][0]
dp[i][0]=[(a1+max(0,j-b1),j)]
for i,j in enumerate(l,1):
for k in range(1,min(K+1,i+1)):
tl=dp[i-1][k-1]
for a1,b1 in dp[i-1][k]:
tl.append((a1+max(0,j-b1),j))
tl.sort(reverse=True)
tl.append((-1,-1))
x=0
l1=[]
while len(tl)-1>x:
a1,b1=tl[x]
l1.append(tl[x])
x+=1
while tl[x][0]==a1:
x+=1
dp[i][k]=l1
a=dp[-1][-1]
a.sort()
print((a[0][0]))
|
p02864
|
N,K= list(map(int,input().split()))
H= list(map(int,input().split()))
def dpinit(ps, val=0):
res = [val for i in [0]*ps[-1]]
for i in ps[:-1][::-1]:
res = [res.copy() for k in [0]*i]
return res
H = [0] + H + [0]
dp = dpinit((N+2,K+2))
for i in range(1,N+2):
for j in range(K+1):
l = min(j+1,i)
cand = [dp[i-k][j-k+1] + max(0, H[i]-H[i-k]) for k in range(1,l+1)]
dp[i][j] = min(cand)
print((dp[N+1][K]))
|
N,K= list(map(int,input().split()))
H= list(map(int,input().split()))
def dpinit(ps, val=0):
res = [val for i in [0]*ps[-1]]
for i in ps[:-1][::-1]:
res = [res[:] for k in [0]*i]
return res
H = [0] + H + [0]
dp = dpinit((N+2,K+2))
for i in range(1,N+2):
for j in range(K+1):
l = min(j+1,i)
cand = [dp[i-k][j-k+1] + max(0, H[i]-H[i-k]) for k in range(1,l+1)]
dp[i][j] = min(cand)
print((dp[N+1][K]))
|
p02864
|
def main():
N, K = (int(i) for i in input().split())
H = [0] + [int(i) for i in input().split()]
if N == K:
return print(0)
elif K == 0:
ans = 0
for i in range(N):
ans += max(H[i+1] - H[i], 0)
return print(ans)
dp = [[10**10]*(N-K+1) for i in range(N+1)]
dp[0][0] = 0
for i, h in enumerate(H):
if i == 0:
continue
dp[i][1] = h
for i in range(1, N+1):
for j in range(1, N-K+1):
for x in range(1, i):
dp[i][j] = min(dp[i][j], dp[x][j-1] + max(0, H[i] - H[x]))
ans = 10**10
for i in range(N+1):
# print(dp[i])
ans = min(ans, dp[i][N-K])
print(ans)
if __name__ == '__main__':
main()
|
def main():
import sys
input = sys.stdin.buffer.readline
N, K = (int(i) for i in input().split())
H = [0] + [int(i) for i in input().split()]
if N == K:
return print(0)
elif K == 0:
ans = 0
for i in range(N):
ans += max(H[i+1] - H[i], 0)
return print(ans)
dp = [[10**10]*(N-K+1) for i in range(N+1)]
dp[0][0] = 0
for i, h in enumerate(H):
if i == 0:
continue
dp[i][1] = h
for i in range(1, N+1):
for j in range(1, N-K+1):
for x in range(1, i):
dp[i][j] = min(dp[i][j], dp[x][j-1] + max(0, H[i] - H[x]))
ans = 10**10
for i in range(N+1):
# print(dp[i])
ans = min(ans, dp[i][N-K])
print(ans)
if __name__ == '__main__':
main()
|
p02864
|
def main():
import sys
input = sys.stdin.buffer.readline
N, K = (int(i) for i in input().split())
H = [0] + [int(i) for i in input().split()]
if N == K:
return print(0)
elif K == 0:
ans = 0
for i in range(N):
ans += max(H[i+1] - H[i], 0)
return print(ans)
dp = [[10**10]*(N-K+1) for i in range(N+1)]
dp[0][0] = 0
for i, h in enumerate(H):
if i == 0:
continue
dp[i][1] = h
for i in range(1, N+1):
for j in range(1, N-K+1):
for x in range(1, i):
dp[i][j] = min(dp[i][j], dp[x][j-1] + max(0, H[i] - H[x]))
ans = 10**10
for i in range(N+1):
# print(dp[i])
ans = min(ans, dp[i][N-K])
print(ans)
if __name__ == '__main__':
main()
|
def main():
N, K = (int(i) for i in input().split())
H = [0] + [int(i) for i in input().split()]
# 1-indexed
if N == K:
return print(0)
elif K == 0:
ans = 0
for i in range(N):
ans += max(H[i+1] - H[i], 0)
return print(ans)
dp = [[10**12]*(N-K+1) for _ in range(N+1)]
for x in range(N+1):
dp[x][1] = H[x]
for y in range(2, N-K+1):
for x in range(N+1):
for i in range(1, x):
dp[x][y] = min(dp[x][y], dp[i][y-1] + max(0, H[x] - H[i]))
ans = dp[0][N-K]
for i in range(1, N+1):
ans = min(ans, dp[i][N-K])
print(ans)
if __name__ == '__main__':
main()
|
p02864
|
from collections import defaultdict
n, k = list(map(int, input().split()))
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0, 0] = 0
for h in hhh:
ndp = defaultdict(lambda: INF)
for (changed, prev_h), operate in list(dp.items()):
if h == prev_h:
ndp[changed, h] = min(ndp[changed, h], operate)
elif h > prev_h:
ndp[changed, h] = min(ndp[changed, h], operate + h - prev_h)
if changed < k:
ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
else:
ndp[changed, h] = min(ndp[changed, h], operate)
if changed < k:
ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
dp = ndp
print((min(dp.values())))
|
from collections import defaultdict
n, k = list(map(int, input().split()))
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0] = 0
mask1 = (1 << 10) - 1
mask2 = ((1 << 63) - 1) ^ mask1
for h in hhh:
ndp = defaultdict(lambda: INF)
h_key = h << 10
for changed_prev_h, operate in list(dp.items()):
changed = changed_prev_h & mask1
prev_h = changed_prev_h >> 10
if h == prev_h:
key = h_key + changed
ndp[key] = min(ndp[key], operate)
elif h > prev_h:
key = h_key + changed
ndp[key] = min(ndp[key], operate + h - prev_h)
if changed < k:
key = changed_prev_h + 1
ndp[key] = min(ndp[key], operate)
else:
key = h_key + changed
ndp[key] = min(ndp[key], operate)
if changed < k:
key = changed_prev_h + 1
ndp[key] = min(ndp[key], operate)
# print(h)
# print(dict(dp))
# print(dict(ndp))
dp = ndp
print((min(dp.values())))
|
p02864
|
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list([int(x)-1 for x in input().split()])
def II(): return int(eval(input()))
def IF(): return float(eval(input()))
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')
from copy import deepcopy
#solve
def solve():
n, k = LI()
h = LI()
d = defaultdict(int)
d[(0, 0)] = 0
for i in range(n):
nd = defaultdict(lambda: inf)
for key, value in list(d.items()):
a, b = key
nd[(h[i], b)] = min(nd[(h[i], b)], value + (h[i] - a if h[i] > a else 0))
if b + 1 > k:
continue
nd[(a, b + 1)] = min(nd[(a, b + 1)], value)
d = nd
ans = inf
for i in range(n):
for j in range(k + 1):
ans = min(ans, d[(h[i], j)])
print(ans)
return
#main
if __name__ == '__main__':
solve()
|
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list([int(x)-1 for x in input().split()])
def II(): return int(eval(input()))
def IF(): return float(eval(input()))
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')
from copy import deepcopy
#solve
def solve():
n, k = LI()
h = [0] + LI()
d = defaultdict(int)
d[(0, 0)] = 0
for i in range(1, n + 1):
nd = defaultdict(lambda: inf)
for key, value in list(d.items()):
a, b = key
if nd[(i, b)] > value + (h[i] - h[a] if h[i] > h[a] else 0):
nd[(i, b)] = value + (h[i] - h[a] if h[i] > h[a] else 0)
if b + 1 > k:
continue
if nd[(a, b + 1)] > value:
nd[(a, b + 1)] = value
d = nd
ans = inf
for i in range(n + 1):
for j in range(k + 1):
ans = min(ans, d[(i, j)])
print(ans)
return
#main
if __name__ == '__main__':
solve()
|
p02864
|
n,k = list(map(int, input().split( )))
h = list(map(int, input().split( )))
#h = [0]+h#h[0]=0追加
inf = 10**15
dp = [[inf]*n for _ in range(n+1)] #dp[i][j]右端がi、j+1本残す
mn = h[0]
for i in range(n):
mn = min(mn,h[i])
dp[i][0] = min(mn,h[i])
for i in range(n):##右端
for j in range(i+1):#本数
for t in range(i):#右から2番目,
dp[i][j] = min(dp[i][j], dp[t][j-1] + max(h[i]-h[t], 0))
ans = inf
for i in range(n):
ans = min(ans, dp[i][n-k-1])
print(ans)
|
n,k = list(map(int, input().split( )))
if n==k:
print((0))
exit()
h = list(map(int, input().split( )))
#h = [0]+h#h[0]=0追加
inf = 10**15
dp = [[inf]*n for _ in range(n+1)] #dp[i][j]右端がi、j+1本残す
mn = h[0]
for i in range(n):
#mn = min(mn,h[i])
dp[i][0] = h[i]#min(mn,h[i])
for i in range(1,n):##右端
for j in range(i+1):#本数
for t in range(j-1,i):#右から2番目,
dp[i][j] = min(dp[i][j], dp[t][j-1] + max(h[i]-h[t], 0))
ans = inf
for i in range(n):
ans = min(ans, min(dp[i][n-k-1:]))###
print(ans)
|
p02864
|
def main():
n, K = list(map(int, input().split()))
H = list(map(int, input().split()))
s = sorted(set(H+[0]))
d = {i: j for j, i in enumerate(s)}
l = len(s)
m = max(s)
a = [m-i for i in s]
dp = [[10**13]*l for _ in range(K+1)]
dp[0][0] = 0
for h in H:
dh = d[h]
dp2 = [[10**13]*l for _ in range(K+1)]
t = [[i+j for i, j in zip(a, kk)] for kk in dp]
min_s = [[dp[i][j] for j in range(l)] for i in range(K+1)]
for i in range(K+1):
for j in range(l-2, -1, -1):
min_s[i][j] = min(min_s[i][j+1], min_s[i][j])
for j in range(1, l):
t[i][j] = min(t[i][j-1], t[i][j])
for j in range(l):
t[i][j] = t[i][j]-a[j]
for i in range(K):
for j in range(l):
dp2[i+1][j] = min(min_s[i][j], t[i][j])
for i in range(K+1):
dp2[i][dh] = min(dp2[i][dh], min(
[dp[i][j]+max(h-s[j], 0) for j in range(l)]))
dp = dp2
print((min([min(i) for i in dp])))
main()
|
def main():
n, K = list(map(int, input().split()))
H = list(map(int, input().split()))
s = sorted(set(H+[0]))
d = {i: j for j, i in enumerate(s)}
l = len(s)
m = max(s)
a = [m-i for i in s]
dp = [[10**13]*l for _ in range(K+1)]
dp[0][0] = 0
for h in H:
dh = d[h]
dp2 = [[0]*l for _ in range(K+1)]
dp2[0] = [10**13]*l
t = [[0]*l for _ in range(K)]
for i in range(K):
for j in range(l):
t[i][j] = dp[i][j]+a[j]
min_s = [[10**13]*l for i in range(K+1)]
for i in range(K):
for j in range(l-2, -1, -1):
min_s[i][j] = min(dp[i][j+1], min_s[i][j])
for j in range(1, l):
t[i][j] = min(t[i][j-1], t[i][j])
for j in range(l):
t[i][j] = t[i][j]-a[j]
for i in range(K):
for j in range(l):
dp2[i+1][j] = min(min_s[i][j], t[i][j])
for i in range(K+1):
temp = 10**13
for j in range(l):
temp = min(temp, dp[i][j]+max(h-s[j], 0))
dp2[i][dh] = min(dp2[i][dh], temp)
dp = dp2
print((min([min(i) for i in dp])))
main()
|
p02864
|
N, K = list(map(int, input().split()))
H = list(map(int, input().split())) + [0]
dp = [[10**12]*(K+2) for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
for j in range(min(i+1, K) + 1):
for k in range(j + 1):
dp[i+1][j] = min(dp[i+1][j], dp[i-k][j-k] + max(H[i] - H[i-k-1], 0))
ans = min(dp[-1])
for i in range(K):
ans = min(ans, dp[N-i][K-i])
print(ans)
|
N, K = list(map(int, input().split()))
H = list(map(int, input().split())) + [0]
dp = [[10**12]*(K+2) for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
for j in range(min(i+1, K) + 1):
for k in range(j + 1):
dp[i+1][j] = min(dp[i+1][j], dp[i-k][j-k] + max(H[i] - H[i-k-1], 0))
ans = min(dp[-1])
for i in range(K+1):
ans = min(ans, dp[N-i][K-i])
print(ans)
|
p02864
|
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1
def main():
N,K=map(int,input().split())
N+=2
H=[0]+list(map(int,input().split()))+[0]
edge=[[] for _ in range(N*(K+1))]
for i in range(N):
for j in range(K+1):
for k in range(K+1-j):
if i+k+1<N and N-1-i>=K-(k+j):
edge[i*(K+1)+j].append((max(H[i+k+1]-H[i],0),(i+k+1)*(K+1)+j+k))
from heapq import heappop,heappush
def dijkstra(start,n,edges):
d=[INF]*n
used=[False]*n
d[start]=0
used[start]=True
edgelist=[]
for edge in edges[start]:
heappush(edgelist,edge)
while edgelist:
minedge=heappop(edgelist)
if used[minedge[1]]:
continue
v=minedge[1]
d[v]=minedge[0]
used[v]=True
for edge in edges[v]:
if not used[edge[1]]:
heappush(edgelist,(edge[0]+d[v],edge[1]))
return d
d=dijkstra(0,N*(K+1),edge)
print(min(d[(N-1)*(K+1):]))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1
def main():
N,K=map(int,input().split())
N+=1
H=[0]+list(map(int,input().split()))+[0]
dp=[[INF]*(K+1) for _ in range(N+1)]
dp[0][0]=0
for i in range(N):
for j in range(K+1):
for k in range(j,K+1):
if i-(k-j)>=0:
dp[i+1][k]=min(dp[i+1][k],dp[i-(k-j)][j]+max(H[i+1]-H[i-(k-j)],0))
pass
print(dp[-1][-1])
if __name__ == '__main__':
main()
|
p02864
|
N, K = list(map(int, input().split()))
H = [0] + [int(a) for a in input().split()]
X = [[1<<100] * (N-K+1) for _ in range(N+1)]
X[0][0] = 0
for i in range(1, N+1):
for j in range(1, min(i+1, N-K+1)):
X[i][j] = min([X[ii][j-1] + max(H[i] - H[ii], 0) for ii in range(i)])
print((min([x[-1] for x in X])))
|
N, K = list(map(int, input().split()))
H = [0] + list(map(int, input().split()))
dp = [[10 ** 100] * (N-K+1) for _ in range(N+1)]
dp[0][0] = 0
for x in range(1, N+1):
for y in range(1, min(x+1, N-K+1)):
dp[x][y] = min([dp[i][y-1] + max(H[x] - H[i], 0) for i in range(x)])
print((min([dp[i][N-K] for i in range(N+1)])))
|
p02864
|
from functools import lru_cache
n, k = list(map(int, input().split()))
h = [0] + list(map(int, input().split())) + [0]
INF = 10 ** 18
@lru_cache(maxsize=10**9)
def solve(i, nokori):
if i == 0:
return 0
res = INF
for j in range(nokori + 1):
if i - 1 - j < 0:
break
diff = max(h[i] - h[i - 1 - j], 0)
res = min(solve(i - 1 - j, nokori - j) + diff, res)
return res
print((solve(n + 1, k)))
|
from functools import lru_cache
n, k = list(map(int, input().split()))
h = [0] + list(map(int, input().split())) + [0]
INF = 10 ** 18
@lru_cache(maxsize=None)
def solve(i, nokori):
if i == 0:
return 0
res = INF
for j in range(nokori + 1):
if i - 1 - j < 0:
break
diff = max(h[i] - h[i - 1 - j], 0)
res = min(solve(i - 1 - j, nokori - j) + diff, res)
return res
print((solve(n + 1, k)))
|
p02864
|
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
n,k = [int(i) for i in readline().split()]
a = [0]+[int(i) for i in readline().split()] + [0]
n += 2
INF = 10**18
diff = [0]
for i in range(n-1):
diff.append(max(a[i+1]-a[i],0))
from itertools import accumulate
acc = list(accumulate(diff))
ans = {}
def calc(p,q,k):
if (p,q,k) in ans: return ans[(p,q,k)]
if k == 0:
res = acc[q] - acc[p]
elif k == q-p-1:
res = max(0,a[q] - a[p])
else:
res = INF
for i in range(p+1,q):
for l in range(min(k+1,i-p)):
if k-l > q-p-1: break
#if p ==1 and q == 4 and k == 1: print(i,l)
res = min(res, calc(p,i,l)+calc(i,q,k-l))
#print(p,q,k,res)
ans[(p,q,k)] = res
return res
#print(acc)
#print(a,n)
print((calc(0,n-1,k)))
#print(calc(0,n-1,k))
|
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
n,k = [int(i) for i in readline().split()]
a = [0]+[int(i) for i in readline().split()]
n += 1
INF = 10**18
K = n-k-1
dp = [[INF]*n for _ in range((K+1))]
dp[0][0] = 0
for i in range(1,n):
ndp = [c[:] for c in dp]
for l in range(min(i,K)):
for now in range(0,i):
ndp[l+1][i] = min(ndp[l+1][i], ndp[l][now]+max(0,a[i]-a[now]))
dp = ndp
#print(dp)
#print(dp[-1])
print((min(dp[-1])))
|
p02864
|
N, K = list(map(int, input().split()))
D = [Di for Di in input().split()]
for n in range(N, 1000000000):
n = str(n)
flag = True
for i in range(len(str(n))):
if n[i] in D:
flag = False
break
if flag is True:
print(n)
exit()
|
N, K = list(map(int, input().split()))
D = [Di for Di in input().split()]
for n in range(N, 1000000000):
n = str(n)
flag = True
for ni in n:
if ni in D:
flag = False
break
if flag:
print(n)
exit()
|
p04045
|
n, k = list(map(int, input().split()))
list_D = set(map(str, input().split()))
num = n
ans = -1
while True:
S = set(list(str(num)))
cnt = 0
for s in S:
if s in list_D:
cnt += 1
if cnt == 0:
ans = num
break
num += 1
print(ans)
|
n, k = list(map(int, input().split()))
list_D = list(map(str, input().split()))
num = n
ans = -1
while True:
S = list(str(num))
cnt = 0
for s in S:
if s in list_D:
cnt += 1
if cnt == 0:
ans = num
break
num += 1
print(ans)
|
p04045
|
#!/usr/bin/env python3
import sys
def solve(N: int, K: int, D: "List[int]"):
while True:
for d in D:
strn=str(N)
if str(d) in strn:
break
else:
print(N)
return
N+=1
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
K = int(next(tokens)) # type: int
D = [int(next(tokens)) for _ in range(K)] # type: "List[int]"
solve(N, K, D)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import sys
def solve(N: int, K: int, D: "List[int]"):
D = list(map(str,D))
while True:
for d in D:
if d in str(N):
N += 1
break
else:
print(N)
break
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
K = int(next(tokens)) # type: int
D = [int(next(tokens)) for _ in range(K)] # type: "List[int]"
solve(N, K, D)
if __name__ == '__main__':
main()
|
p04045
|
total, k = list(map(int, input().split()))
ds = list(input().split())
ans = total
while True:
flag = False
for d in ds:
if d in list(str(ans)):
flag = True
if flag:
ans += 1
else:
print(ans)
exit(0)
|
total, k = list(map(int, input().split()))
ds = list(input().split())
for i in range(total,total*10+2):
for d in ds:
if d in list(str(i)):
break
else:
print(i)
exit(0)
|
p04045
|
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
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())
N, K = list(map(int, input().split()))
D = input().split()
for n in range(N, 100000):
s = str(n)
ok = True
for c in s:
if c in D:
ok = False
if ok:
print(n)
break
|
N, K = list(map(int, input().split()))
D = set(input().split())
for n in range(N, N * 10 + 1):
ok = True
for c in str(n):
if c in D:
ok = False
if ok:
print(n)
break
|
p04045
|
n, k = list(map(int, input().split()))
d = list(map(int, input().split()))
n_list = list(str(n))
n_list = [int(num) for num in n_list]
num = {1,2,3,4,5,6,7,8,9,0}
d_set = set(d)
empty = set()
#print(set(n_list))
#print(d_set)
#print(set(n_list) & d_set)
while(1):
n_list = list(str(n))
n_list = [int(num) for num in n_list]
if(set(n_list) & d_set == empty):
print(n)
break
n += 1
|
import sys
N, K = list(map(int, input().split()))
d = list(map(int, input().split()))
d_set = set(d)
num_set = set([1,2,3,4,5,6,7,8,9,0])
enable = num_set - d_set
#print(type(enable))
#print(enable)
def dfs(s):
#print(s)
global ans
# すでにN以上の場合はこの先を探索しない
if s != "":
if int(s) >= N:
#print(s)
ans.append(int(s))
return
for num in enable:
if len(s) == 0 and num == 0:
continue
else:
(dfs(s+str(num)))
return
ans = []
dfs("")
#print(ans)
print((min(ans)))
|
p04045
|
kingaku, n = input().split()
no_num = input().split()
result = []
ok_num = []
kuriage_num = [-1, 0]
def kuriage(l):
for i in ok_num:
if result[l] < i:
kuriage_num = [l, i]
return
if l <= 0:
return
return kuriage(l-1)
#使える数字のリストを作成
for i in range(10):
if not str(i) in no_num:
ok_num.append(str(i))
set_flg = False
for i in kingaku:
set_flg = True
for j in ok_num:
if i == j:
set_flg = False
result.append(j)
break
elif i < j:
result.append(j)
print(("".join(result).ljust(len(kingaku), ok_num[0])))
exit()
break
if set_flg:
n = 0
if ok_num[0] == '0':
n = 1
print((ok_num[n].ljust(len(kingaku)+1, ok_num[0])))
exit()
print((''.join(result)))
|
kingaku, n = input().split()
no_num = input().split()
ok_num = []
result = []
for i in range(10):
if not str(i) in no_num:
ok_num.append(str(i))
set_flg = False
for i in kingaku:
set_flg = True
for j in ok_num:
if i == j:
set_flg = False
result.append(j)
break
elif i < j:
result.append(j)
print(("".join(result).ljust(len(kingaku), ok_num[0])))
exit()
break
if set_flg:
n = 0
if ok_num[0] == '0':
n = 1
print((ok_num[n].ljust(len(kingaku)+1, ok_num[0])))
exit()
print((''.join(result)))
|
p04045
|
N, L = list(map(int, input().split()))
S = {int(x) for x in input().split()}
flag = False
while flag == False:
if N%10 in S:
N += 1
continue
if int((N%100-N%10)/10) in S and N >= 10:
N += 1
continue
if int((N%1000-N%100)/100) in S and N >= 100:
N += 1
continue
if int((N%10000-N%1000)/1000) in S and N >= 1000:
N += 1
continue
if int((N%100000-N%10000)/10000) in S and N >= 10000:
N += 1
continue
flag = True
print(N)
|
N, L = list(map(int, input().split()))
S = {int(x) for x in input().split()}
flag = False
while 1:
if N%10 in S:
N += 1
continue
if int((N%100-N%10)/10) in S and N >= 10:
N += 1
continue
if int((N%1000-N%100)/100) in S and N >= 100:
N += 1
continue
if int((N%10000-N%1000)/1000) in S and N >= 1000:
N += 1
continue
if int((N%100000-N%10000)/10000) in S and N >= 10000:
N += 1
continue
break
print(N)
|
p04045
|
N, K = list(map(int, input().split()))
D = set(map(str, input().split()))
for i in range(N, 100000):
a = list(str(i))
a = set(a)
if a & D == set():
print(i)
break
|
N, K = list(map(int, input().split()))
D = set(list(input().split()))
while True:
if set(list(str(N))) & D:
N += 1
else:
print(N)
exit()
|
p04045
|
Num = [int(n) for n in input().rstrip().split()]
D = [int(n) for n in input().rstrip().split()]
for i in range(Num[0],100000):
if len(set([str(n) for n in D]) & set(str(i))) == 0:
print((int(i)))
break
|
Num = [int(n) for n in input().rstrip().split()]
D = [int(n) for n in input().rstrip().split()]
# numbers = [ n for n in range(10) if not n in D]
flag = 0
for i in range(Num[0],10*Num[0]+1):
for j in str(i):
if int(j) in D:
flag = 1
break
if flag == 0:
print(i)
break
else:
flag =0
|
p04045
|
Num = [int(n) for n in input().rstrip().split()]
D = [int(n) for n in input().rstrip().split()]
# numbers = [ n for n in range(10) if not n in D]
flag = 0
for i in range(Num[0],10*Num[0]+1):
for j in str(i):
if int(j) in D:
flag = 1
break
if flag == 0:
print(i)
break
else:
flag =0
|
N ,K = list(map(int,input().split()))
D = [int(n) for n in input().split()]
flag = False
for i in range(N,100000):
N = i
while i > 0:
flag = True
if i%10 in D:
flag = False
break
else:
i //=10
if flag == True:
print(N)
break
|
p04045
|
import sys
from bisect import bisect_left
def input(): return sys.stdin.readline().strip()
def main():
N, K = list(map(int, input().split()))
D = set(map(int, input().split()))
while True:
check = True
for c in str(N):
if int(c) in D:
check = False
if check:
print(N)
return
N += 1
if __name__ == "__main__":
main()
|
import sys
from itertools import product
def input(): return sys.stdin.readline().strip()
def main():
"""
itertools.productを使うと高速なようなので写経
参考:https://atcoder.jp/contests/abc042/submissions/16188969
"""
N, K = list(map(int, input().split()))
D = set(map(int, input().split()))
ok = [i for i in range(10) if i not in D]
l = len(str(N))
if int(str(ok[-1]) * l) < N:
if ok[0] == 0:
print((ok[1] * 10 ** l))
else:
print((str(ok[0]) * (l + 1)))
else:
for x in product(ok, repeat=l):
x = int("".join(map(str, x)))
if x >= N:
print(x)
return
if __name__ == "__main__":
main()
|
p04045
|
def main():
N, K = list(map(int, input().split()))
D = set(map(int, input().split()))
numset = set(range(0,10))
d = numset.difference(D)
for n in range(N, pow(10, 6) + 10):
check = set(list(str(n)))
ngflag = False
for i in check:
if int(i) in D:
ngflag = True
break
if not ngflag:
break
print(n)
if __name__ == "__main__":
main()
|
def minN(N:int, usable:list, restrict=True):
usable.sort()
keta = False
if restrict:
for i in usable:
if i >= N:
return str(i)
# 桁が増える
return '1'+str(usable[0])
else:
return str(usable[0])
def rote(N:list, D:set, d:set):
ans = []
flag = True
lenNstr = len(N)
for i, n in enumerate(N):
n = int(n)
keta = 10**(len(N) - i - 1)
if flag:
if n in D:
ans.append(int(minN(n, d)) * keta)
flag = False
else:
ans.append(keta * n)
else:
ans.append(keta * min(d))
return sum(ans)
def main():
N, K = list(map(int, input().split()))
D = set(map(int, input().split()))
numset = set(range(0,10))
d = list(numset.difference(D))
d.sort()
for _ in range(10):
Nstr = list(str(N))
ans = rote(Nstr, D, d)
N = ans
print(ans)
if __name__ == "__main__":
main()
|
p04045
|
n, k = list(map(int, input().split()))
d_array = [int(x) for x in input().split()]
for i in range(n, 100000):
flag = True
price = str(i)
for d in d_array:
str_d = str(d)
if str_d in price:
flag = False
else:
if flag:
print(i)
exit()
|
n, k = list(map(int, input().split()))
d_array = [str(x) for x in input().split()]
price = 0
while True:
flag = True
for s in str(price):
if s in d_array:
flag = False
if price >= n and flag:
print(price)
break
price+=1
|
p04045
|
def main():
n, k = list(map(int, input().split()))
D = list(map(int, input().split()))
while 1:
f = 0
hoge = str(n)
for i in range(len(hoge)):
for j in range(k):
if(int(hoge[i]) == D[j]):
f = 1
break
if f == 1:
break
if f == 1:
break
if f == 0:
print(n)
break
n += 1
if __name__ == "__main__":
main()
|
def main():
N, K = list(map(int, input().split()))
D = list(input().split())
i = 0
while True:
S = str(N)
f = True
for s in S:
if s in D:
f = False
break
if f:
break
N += 1
print(N)
if __name__ == "__main__":
main()
|
p04045
|
def getN():
return int(eval(input()))
def getNM():
return list(map(int, input().split()))
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(eval(input())) for i in range(intn)]
from collections import defaultdict, deque
from sys import exit
import heapq
import math
import copy
from bisect import bisect_left, bisect_right
import sys
sys.setrecursionlimit(1000000000)
# list(map(int, input().split()))
N, K = getNM()
intlist = [i for i in range(10)]
D = getList()
for i in D:
if i in D:
intlist.pop(intlist.index(i))
anslist = []
def dfs(i, num):
anslist.append(num)
if i < 5:
for j in intlist:
newnum = int(str(num) + str(j))
dfs(i + 1, newnum)
for i in intlist:
if i != 0:
dfs(1, i)
anslist.sort()
for i in anslist:
if i >= N:
ans = i
break
print(ans)
|
def getN():
return int(eval(input()))
def getNM():
return list(map(int, input().split()))
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(eval(input())) for i in range(intn)]
from collections import defaultdict, deque
from sys import exit
import heapq
import math
import copy
from bisect import bisect_left, bisect_right
import sys
sys.setrecursionlimit(1000000000)
N, K = getNM()
intlist = [i for i in range(10)]
D = getList()
for i in D:
if i in D:
# 嫌いな数字を消す
intlist.pop(intlist.index(i))
anslist = []
# intlist内の数字でできる5桁以内の数字を全列挙(5桁の数字も列挙するのは無駄な気もする)
# dfsで解いてる人はあんまりいない
# 基本的に全探索
def dfs(i, num):
anslist.append(num)
# num < Nの条件で計算量を制限
if i < 5 and num < N:
for j in intlist:
newnum = int(str(num) + str(j))
dfs(i + 1, newnum)
for i in intlist:
if i != 0:
dfs(1, i)
anslist.sort()
for i in anslist:
if i >= N:
ans = i
break
print(ans)
|
p04045
|
from itertools import product
n,k = list(map(int, input().split()))
d = list(map(int, input().split()))
nums = []
for i in range(10):
if i not in d: nums.append(i)
for i in range(len(str(n)), 6):
for j in product(nums, repeat=i):
t = ""
if j[0] != 0:
for k in j:
t += str(k)
if int(t) >= n:
print(t)
exit()
|
from itertools import product
n,k = list(map(int, input().split()))
d = list(map(int, input().split()))
nums = []
for i in range(10):
if i not in d: nums.append(i)
m = str(n)
for i in range(len(m), len(m)+2):
for j in product(nums, repeat=i):
ans = ""
for k in j: ans += str(k)
if int(ans) >= n:
print(ans)
exit()
|
p04045
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.