Problem:


Score : 700 points

Problem Statement

We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}).
Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.

Snuke has an integer sequence s, which is initially empty.
For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:

If s does not contain X_i: add X_i to the end of s.

If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.

Find the elements of s after Snuke finished the operations.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq K \leq 10^{12}

1 \leq A_i \leq 2 \times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 \cdots A_{N-1}

Output

Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.

Sample Input 1

3 2
1 2 3

Sample Output 1

2 3

In this case, X=(1,2,3,1,2,3).
We will perform the operations as follows:

i=0: s does not contain 1, so we add 1 to the end of s, resulting in s=(1).

i=1: s does not contain 2, so we add 2 to the end of s, resulting in s=(1,2).

i=2: s does not contain 3, so we add 3 to the end of s, resulting in s=(1,2,3).

i=3: s does contain 1, so we repeatedly delete the element at the end of s as long as s contains 1, which causes the following changes to s: (1,2,3)→(1,2)→(1)→().

i=4: s does not contain 2, so we add 2 to the end of s, resulting in s=(2).

i=5: s does not contain 3, so we add 3 to the end of s, resulting in s=(2,3).

Sample Input 2

5 10
1 2 3 2 3

Sample Output 2

3

Sample Input 3

6 1000000000000
1 1 2 2 3 3

Sample Output 3

s may be empty in the end.

Sample Input 4

11 97
3 1 4 1 5 9 2 6 5 3 5

Sample Output 4

9 2 6



Sample input:
3 2
1 2 3


Sample output:
2 3

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,k = [int(i) for i in readline().split()]
a = [int(i) for i in readline().split()]

memo = dict()
res = [-1]*(2*n)
for i,c in enumerate(a*2):
    if c in memo:
        res[memo[c]] = i+1
    memo[c] = i


res2 = [0]*(n)

def dfs(i):
    if res[i] < n:
        res2[i] = dfs(res[i])
    else:
        res2[i] = res[i]
    return res2[i]

for i in range(n): dfs(i)
#print(res)        
#print(res2)        


cycle = [0]
offset = 0
now = res2[0]-n

while now != 0:
    if now == n:
        offset += 1
        break
    else:
        cycle.append(now)
        now = res2[now]-n


#print(cycle,offset)

l = len(cycle)
k-=1
k %= (l+offset)

#print("k =",k)

if k != l: ans = p = cycle[k]
else: ans = p = n+1
while p <= n:
    ans = p
    p = res[p]
#    print(ans,p)

if ans >= n: exit()
else:
    s = []
    for i in range(ans,n):
        ai = str(a[i])
        if ai not in s:
            s.append(ai)
        else:
            while ai in s: s.pop()
    
print(" ".join(s))

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
A=[int(i) for i in input().split()]
AA=[0]*n
B=[2*n+1]*(2*(10**5)+1)
for i in reversed(range(n)):
  B[A[i]]=n+i+1
for i in reversed(range(n)):
  AA[i]=B[A[i]]-(i+1)
  B[A[i]]=i+1
count,index,inc=0,0,0
while count<n*k:
  index=(index+inc)%n
  inc=AA[index]+1
  count+=inc  
  if count%n==0:
    count*=(n*k)//count

count-=inc
d=n*k-count
Ans1=A+A
Ans1=Ans1[index:index+d]
Ans2=AA+AA
Ans2=Ans2[index:index+d]
Ans=[]
i=0
while i<d:
  if i+Ans2[i]>=d:
    Ans.append(Ans1[i])
    i+=1
  else:
    i+=Ans2[i]+1
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().rstrip().split(' '))
A = list(map(int,input().rstrip().split(' ')))
s = []
sl = {}
for i in range(K):
        for j in A:
                if not j in s:
                    s.append(j)
                    sl[j] = s.index(j)
                else:
                        s = s[:sl[j]]
print(*s)

Submission status: Time Limit Exceeded

Solution code:
n,k = [int(x) for x in input().split(" ")]
a_list = [int(x) for x in input().split(" ")]
res = []
last_results = []
for j in range(k):
    for i in range(n):
        x = str(a_list[i])
        try:
            idx = res.index(x)
            res = res[:idx]
        except Exception as e:
            res.append(x)
    if tuple([]) in last_results:
        break
    else:
        last_result = res
    last_results.append(tuple(res))
print(" ".join(list(last_results[(k-1) % len(last_results)])))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())

arr = list(map(int, input().split()))

res = {}
start = None

if n == 1:
    if k % 2:
        print(*arr)
    else:
        print(*[])
    exit()

for i in range(1, k + 1):
    if not start:
        response = []
        for elem in arr:
            if elem not in response:
                response.append(elem)
            else:
                idx = response.index(elem)
                response = response[:idx]
        if not response:
            print(*response)
            exit()
        start = response[0]
        res[i] = 0
        continue

    idx = -1
    while start in arr[idx + 1:]:
        idx += arr[idx+1:].index(start) + 2
        if idx < len(arr):
            start = arr[idx]
        else:
            break

    res[i] = idx
    if idx == len(arr):
        k %= len(res)
        if not k:
            k = len(res)
        break

answer = res[k]
response = []
for elem in arr[answer:]:
    if elem not in response:
        response.append(elem)
    else:
        idx = response.index(elem)
        response = response[:idx]
print(*response)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
A=[int(i) for i in input().split()]
AA=[0]*n
B=[2*n+1]*(2*(10**5)+1)
for i in reversed(range(n)):
  B[A[i]]=min(B[A[i]],n+i+1)
for i in reversed(range(n)):
  AA[i]=B[A[i]]-(i+1)
  B[A[i]]=i+1
count,index,inc=0,0,0
while count<n*k:
  index=(index+inc)%n
  inc=AA[index]+1
  count+=inc  
  if count%n==0:
    count*=(n*k)//count

count-=inc
d=n*k-count
Ans1=A+A
Ans1=Ans1[index:index+d]
Ans2=AA+AA
Ans2=Ans2[index:index+d]
Ans=[]
i=0
while i<d:
  if i+Ans2[i]>=d:
    Ans.append(Ans1[i])
    i+=1
  else:
    i+=Ans2[i]+1
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
A=[int(i) for i in input().split()]
AA=[0]*n
B=[2*n+1]*(2*(10**5)+1)
for i in reversed(range(n)):
  B[A[i]]=min(B[A[i]],n+i+1)
for i in reversed(range(n)):
  AA[i]=B[A[i]]-(i+1)
  B[A[i]]=i+1
count,index,inc=0,0,0
while count<n*k:
  index=(index+inc)%n
  inc=AA[index]+1
  count+=inc  
  if count%n==0:
    count*=(n*k)//count

count-=inc
d=n*k-count
Ans1=A+A
Ans1=Ans1[index:index+d]
Ans2=AA+AA
Ans2=Ans2[index:index+d]
Ans=[]
i=0
while i<d:
  if i+Ans2[i]>=d:
    Ans.append(Ans1[i])
    i+=1
  else:
    i+=Ans2[i]+1
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
def slimvec(vec):
  i = 0
  tar = vec[i]

  while True:
    try:
      i+=1
      if vec[i]==tar:
        vec = vec[(i+1):]
        i = 0
        tar = vec[i]
        #print(vec)
    except:
      return vec

n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
l = len(a)

i = 0
idx = 0
target = a[i]
count=0
flag=True

while idx!=0 or flag==True:
  if l <= (i+1):
    count+=1
  i = ((i+1)%l)
  #print("i=",i)
  
  if a[i]==target:
    flag=False
    if l <= (i+1):
      count+=1
    i = ((i+1)%l)
    idx = i
    #print("idx=",idx)
    target = a[i]
  else:
    pass
    
#print("count=",count)
if count==1:
  pass
else:
  k = k%count

  vec = a*k
  #print(vec)

  vec = slimvec(vec)

  while True:
    try:
      subvec = vec[(i+1):]
      subslimvec = slimvec(subvec)
      #print(subslimvec)

      if subslimvec==subvec:
        i+=1
      else:
        #print("cut")
        vec = vec[:(i+1)] + subslimvec
        i=0
    except:
      break

  for v in vec:
    print(v, end=" ")

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int, input().split())
A=list(map(int, input().split()))
s=[]
results={}

for i in range(K):
    for x in A:
        if x not in s:
            s.append(x)
        else:
            while x in s:
                s.pop()
    results[i]=s[:]
    if len(s) == 0:
        #print("looped")
        m = K % (i + 1)
        if m == 0:
            print(*s)
        else:
            print(*results[m-1])
        break
else:
    #print("not looped")
    print(*s)

Submission status: Time Limit Exceeded

Solution code:
N , K = map(int, input().split())
a = list(input().split())
#print(a)
a = [int(s) for s in a]
#print(a)
x = []
for i in range(K):
        x += a
p = 0
while True:
#       print(x)
        check = True
        for i in range(p+1,len(x)):
                if x[p] == x[i]:
                        x = x[:p] + x[i+1:]
                        check = False
                        break
        if check:
                p+=1
                if p == len(x): break


for i in range(len(x)-1):
        print("{} ".format(x[i]),end="")
if len(x): print("{}".format(x[-1]))
else: print()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

ans = []
s = set()
q = deque([])

def solve():
  N, K = map(int, input().split())
  A = [int(i) for i in input().split()]
  for i in range(K):
    for a in A:
      if a not in s:
        q.append(a)
        s.add(a)
      else:
        while True:
          out = q.pop()
          s.remove(out)
          if a == out: break
    ans.append(list(q))
    if len(q) == 0: break

  return ans[K % len(ans) - 1]

print(*solve())

Submission status: Time Limit Exceeded

Solution code:
import math

def main():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    dp = {}
    memo = set()
    # arrays = []
    
    L = []
    # K = min(K, K % 10 + 10)
    for k in range(K):
        for a in A:
            # print(L, memo)
            if a not in memo:
                i = len(L)
                L.append(a)
                dp[a] = i
                memo.add(a)
            else:
                i = dp[a]
                L = L[:i]
                # r = memo
                memo = set(L)
                dp = {x: i for i,x in enumerate(L)}
        # if len(arrays) == 0:
        #     arrays.append("".join(L))
        #     continue
        # if "".join(L) in arrays:
        #     loop = len(arrays)
        #     ge = K % loop
        #     L = arrays[ge]
        #     print(k)
        #     break
        # else:
        #     print(arrays)
        #     arrays.append("".join(L))

    print(*L, sep=" ")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/agc036/tasks/agc036_b
from itertools import product
import numpy as np


def calc(N: int, K: int, A: np.ndarray) -> np.ndarray:
    loop_values, rest_iter = calc_until_find_loop(N, K, A)
    loop_len = loop_values.shape[0]
    return loop_values[rest_iter % loop_len]


def calc_until_find_loop(N: int, K: int, A: np.ndarray):  # (loop_values, rest_iter)
    results = []
    values_to_idx = {}
    values = np.array([])
    for i in range(K):
        values = one_iter(N, A, values)
        tup_values = tuple(values)

        if tup_values in values_to_idx:
            return np.array(results[values_to_idx[tup_values] :]), (K - i - 1)

        values_to_idx[tup_values] = len(results)
        results.append(values)

    return np.array([values]), 0


def one_iter(N: int, A: np.ndarray, prev_values: np.ndarray) -> np.ndarray:
    values = prev_values.tolist()
    for j in range(N):
        if A[j] not in values:
            values.append(A[j])
        else:
            while A[j] in values:
                values.pop(-1)
    return np.array(values)


def load_input_as_int_array():
    return np.array([int(v) for v in input().split(" ")])


N, K = load_input_as_int_array()
A = load_input_as_int_array()
result = calc(N, K, A)
print(" ".join([str(v) for v in result]))

Submission status: Time Limit Exceeded

Solution code:
def A():
    line = input().split()
    N = line[0]
    K = int(line[1])
    nums = input().split()
    #print(N, K, nums)

    ans = []
    counter = 0
    cycle = [[]]

    for n in nums:
        if n in ans:
            ans = ans[:ans.index(n)]
        else:
            ans.append(n)
    counter += 1
    cycle.append(ans[:])

    while ans!=[] and counter <= K:
        for n in nums:
            #print(ans)
            if n in ans:
                ans = ans[:ans.index(n)]
            else:
                ans += n
        counter += 1
        cycle.append(ans[:])
    
    #print(counter)
    #print(cycle)
    to_print = cycle[min(len(cycle), K%(len(cycle)-1))]

    print(' '.join(to_print))

A()

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))

dic = {}
result = [0] * N
result_dic = {}
result_dic_index = {}
loop = 0

index = 0
for k in range(K):
    for i in range(N):
        v = dic.get(A[i], None)

        if v is None:
            dic[A[i]] = 1
            result[index] = A[i]
            index += 1
        else:
            while True:
                if result[index - 1] == A[i]:
                    dic.pop(result[index - 1])
                    index -= 1
                    break
                else:
                    dic.pop(result[index - 1])
                    index -= 1
    result_v = result[0:index]
    exist_v = result_dic.get(tuple(result_v), None)
    if exist_v is not None:
        loop = k
        break
    else:
        t = tuple(result_v)
        result_dic[t] = t
        result_dic_index[k] = t

answers = None
if loop == 0:
    answers = result_v
else:
    index = (K - 1) % loop
    answers = result_dic_index[index]

for answer in answers:
    print(answer, end=" ")
print()

Submission status: Time Limit Exceeded

Solution code:
n,k = [int(x) for x in input().split(" ")]
a_list = [int(x) for x in input().split(" ")]
res = []
for j in range(k):
    for i in range(n):
        x = str(a_list[i])
        if not x in res:
            res.append(x)
        else:
            res = res[:res.index(x)]
print(" ".join(res))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
count = 0
s = []
num = list(map(int, input().split()))
while count < K:
  for j in range(len(num)):
    if num[j] not in s:
      s.append(num[j])
    else:
      while num[j] in s:
        s.pop()
  count += 1

if len(s) > 1:
    print(' '.join(map(str,s)))
else:
    print(s[0])

Submission status: Time Limit Exceeded

Solution code:
N_str, K_str = input().split()
N = int(N_str)
K = int(K_str)

A_str = input().split()
A = [int(a) for a in A_str]

s = []

X = []


def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]


for _ in range(K):
    X.extend(A)

for k in range(N * K):
    if not X[k] in s:
        s.append(X[k])

    else:
        inner = my_index_multi(s, X[k])[-1]
        s = s[:inner]

for i in range(len(s)):
    print(s[i], end=' ')

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
As = list(map(int, input().split()))
count = -1
s = []
for k in range(K):
  for a in As:
    i = -1
    for j in range(len(s)):
      if s[j] == a:
        i = j
    if i < 0:
      s.append(a)
    else:
      s = s[0:i]
  #print(s)
  if s == []:
    count = k
    break
#print(count)
if count < 0:
  print(" ".join(map(str, s)))
else:
  K = K%(count+1)
  s = []
  for k in range(K):
    for a in As:
      i = -1
      for j in range(len(s)):
        if s[j] == a:
          i = j
      if i < 0:
        s.append(a)
      else:
        s = s[0:i]
  print(" ".join(map(str, s)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

X = A * 2

Nextcount = [-1] * (2 * (10**5+1))
Nextind = [-1]*N

for i,x in enumerate(X):
    if 0 <= Nextcount[x] < N:
        Nextind[Nextcount[x]] = i

    Nextcount[x] = i

Repeatcount=0
NOW = 0

Repeatcount+=Nextind[NOW]-NOW+1
NOW=(Nextind[NOW]+1)%N

while NOW!=0:
    Repeatcount+=Nextind[NOW]-NOW+1
    NOW=(Nextind[NOW]+1)%N
    

Rep=(N*K)%Repeatcount

from collections import Counter
C=Counter()
s=[]
for i in range(Rep):
    if X[i%N] in C:
        while X[i%N] in C:
            po=s.pop()
            C[po]-=1
            if C[po]==0:
                del C[po]

    else:
        s.append(X[i%N])
        C[X[i%N]]+=1

    #print(s,C)

print(*s)

Submission status: Time Limit Exceeded

Solution code:
N , K = map(int, input().split())
a = list(input().split())
#print(a)
a = [int(s) for s in a]
#print(a)
x = []
for i in range(K):
        x += a
s = []
for i in range(N*K):
        p = x[i]
        check = True
        for j in range(len(s)-1,-1,-1):
                if s[j] == p:
                        check = False
                        s = s[:j]
                        break
        if check:
                s.append(p)

for i in range(len(s)-1):
        print("{} ".format(s[i]),end="")
print("{}".format(s[-1]))

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int, raw_input().split())
a=map(int, raw_input().split())
s=[]

#for i in xrange(k):
i=0
while i != k:
#    print "i="+str(i)
    for j in xrange(n):
#        print "j="+str(j)
        if a[j] in s:
            idx=s.index(a[j])
            s=s[0:idx]
#            for l in range(len(s)-1,-1,-1):
#                print "l="+str(l)
#                if a[j] == s[l]:
#                    s.pop(l)
#                    break
#                else:
#                    s.pop(l)
        else:
            s.append(a[j])
#        print s
    i+=1

print " ".join(map(str, s))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))

B = []
R = []
k = 0
while k < K:
    for a in A:
        if a in B:
            B = B[:B.index(a)]
        else:
            B.append(a)
    R.append(B.copy())
    if len(B) == 0:
        break
    k += 1

if k == K:
    print(" ".join(map(str,B)))
else:
    idx = (K + len(R) - 1) % len(R)
    print(" ".join(map(str, R[idx])))

Submission status: Time Limit Exceeded

Solution code:
N , K = map(int, input().split())
a = list(input().split())
#print(a)
a = [int(s) for s in a]
#print(a)
x = []
for i in range(K):
        x += a
s = []
for i in range(N*K):
        p = x[i]
        if p in s:
                while True:
                        if(s[-1] == p):
                                s.pop()
                                break
                        s.pop()
        else:
                s.append(p)

for i in range(len(s)-1):
        print("{} ".format(s[i]),end="")
print("{}".format(s[-1]))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())

arr = list(map(int, input().split()))

res = {}
s = []

for i in range(1, k + 1):
    for ele in arr:
        if ele not in s:
            s.append(ele)
        else:
            idx = s.index(ele)
            s = s[:idx]
    res[i] = s[:]
    if not s:
        k %= len(res)
        if not k:
            k = len(res)
        answer = res[k]
        print(*answer)
        break
else:
    answer = res[k]
    print(*answer)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
from collections import defaultdict

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

AA = A + A # 2周分
next_same = [None] * (2*N)
last_pos = defaultdict(lambda: None)

for i,a in enumerate(AA):
    j = last_pos[a]
    if j is None:
        last_pos[a] = i
    else:
        next_same[j] = i
        last_pos[a] = i

next_cycle_start = [None] * N

for i,a in enumerate(A[::-1],1):
    i = N - i
    j = next_same[i] + 1
    k = j if j >= N else next_cycle_start[j]
    next_cycle_start[i] = k

x = 0
while True:
    n = next_cycle_start[x]
    q,r = n//N, n%N
    if K > q:
        x = r
        K -= q
    else:
        break

if K == 2:
    answer = []
else:
    answer = []
    while x < N:
        y = next_same[x]
        if y < N:
            x = y + 1
            continue
        else:
            answer.append(str(A[x]))
            x += 1

print(' '.join(answer))

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))

dic = {}
result = []
result_dic = {}
result_dic_index = {}

loop = 0
for k in range(K):
    for i in range(N):
        v = dic.get(A[i], None)
        # print(result, dic, A[i])
        if v is None:
            dic[A[i]] = 1
            result.append(A[i])
        else:
            while True:
                if result[-1] == A[i]:
                    dic.pop(result.pop(-1))
                    break
                else:
                    dic.pop(result.pop(-1))
    exist_v = result_dic.get(tuple(result), None)
    if exist_v is not None:
        loop = k
        break
    else:
        result_dic[tuple(result)] = k
        result_dic_index[k] = tuple(result)

answers = None
if loop == 0:
    answers = result
else:
    index = (K - 1) % loop
    answers = result_dic_index[index]

for answer in answers:
    print(answer, end=" ")
print()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
S = []
for i in range(K):
    n = 0
    for j in A:
        n+=1
        if j in S:
            S = S[:S.index(j)]
        else:
            S.append(j)
    if S == []:
        break
K = K%(i+1)
for i in range(K):
    n = 0
    for j in A:
        n+=1
        if j in S:
            S = S[:S.index(j)]
        else:
            S.append(j)
for i in S:
    print(i,end = " ")
print()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict
N,K = map(int,input().split())
A = list(map(int,input().split()))

#N = 2*10**5
#K = 10**12
#A = [(i % 200000) + 1 for i in range(N)]

def answer(N,K,A):
    s = []
    for i in range(N*K):
        a = A[i%N]
        if a in s:
            s = s[:s.index(a)]
        else:
            s.append(a)
    return s

def solve(N,K,A):
    B = A * 2
    NA = [-1]*N
    d = {}
    for i, b in enumerate(B):
        if b in d:
            if NA[d[b]%N] == -1:
                NA[d[b]%N] = i - d[b]+1
            d[b] = i 
        else:
            d[b] = i

    L = 57
    ds = [NA]
    for i in range(L):
        pre = ds[-1]
        temp = [pre[j] + pre[(pre[j]+j)%N] for j in range(N)]
        ds.append(temp)

    cnt = 0
    i = 0

    L -= 1
    NA = ds[L]
    while True:
        add = NA[i]
        nxt = ((i + add)%N)
        if cnt + add > N*K:
            L -= 1
            if L < 0:
                break
            NA = ds[L]
            continue
        cnt += add
        i = nxt


    s = []
    NA = ds[0]
    while cnt < N*K:
        a = A[i%N]
        add = NA[i%N]
        if add + cnt > N*K:
            s.append(a)
            i = (i+1) % N
            cnt += 1
        else:
            i = (i+add) % N
            cnt += add

    return s
print(*solve(N,K,A))

#import random
#N,K = 2*10**5,2*10**5
#A = [random.randint(1,2*10**5) for i in range(N)]
#solve(N,K,A)
#exit()
#for i in range(100):
#    import random
#    N,K = 100,100
#    A = [random.randint(1,10) for i in range(N)]
#    s1 = answer(N,K,A)
#    s2 = solve(N,K,A)
#    if s1 != s2:
#        print(N,K,A)
#        print(s1)
#        print(s2)
#        break

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, K = mapint()
As = list(mapint())
double_As = As*2
idx_dic = {}
idx_lis = [N+1]*(2*N)
for i in range(N*2-1, -1, -1):
    a = double_As[i]
    if a in idx_dic:
        idx_lis[i] = idx_dic[a]+1
    idx_dic[a] = i
doubling = [[0]*N for _ in range(60)]
accum = [[0]*N for _ in range(60)]
doubling[0] = [i%N for i in idx_lis[:N]]
accum[0] = [a-i for i, a in enumerate(idx_lis[:N])]
for i in range(1, 60):
    for j in range(N):
        doubling[i][j] = doubling[i-1][doubling[i-1][j]]
        accum[i][j] = accum[i-1][j] + accum[i-1][doubling[i-1][j]]
now = 0
cum = 0
cnt = 0
for i in range(59, -1, -1):
    if cum + accum[i][now]>N*K:
        continue
    else:
        cum += accum[i][now]
        now = doubling[i][now]
ans = []
while cum<N*K:
    if cum+accum[0][now]<=N*K:
        cum += accum[0][now]
        now = doubling[0][now]
    else:
        ans.append(As[now])
        now += 1
        cum += 1
print(*ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict

    N, K = map(int, readline().split())
    A = list(map(int, readline().split()))

    c = N * K
    b = 0
    while 2 ** b < c:
        b += 1

    doubling = [[0] * N for _ in range(b + 1)]

    idx = defaultdict(list)
    for i, x in enumerate(A):
        idx[x].append(i)

    for i in range(1, 200001):
        d = idx[i]
        l = len(d)
        for j in range(l):
            cur = d[j]
            nx = d[(j + 1) % l]
            if nx <= cur:
                doubling[0][cur] = N - (cur - nx) + 1
            else:
                doubling[0][cur] = nx - cur + 1

    for i in range(1, b + 1):
        for j in range(N):
            p = doubling[i - 1][j]
            doubling[i][j] = p + doubling[i - 1][(j + p) % N]

    cnt = 0
    cur = 0
    while c - cnt > 200000:
        for i in range(b, -1, -1):
            if cnt + doubling[i][cur] < c:
                cnt += doubling[i][cur]
                cur = cnt % N
                break

    rem = c - cnt
    res = []
    res_set = set()

    while rem > 0:
        num = A[cur]
        if num in res_set:
            while True:
                back = res[-1]
                res.pop()
                res_set.discard(back)
                if back == num:
                    break
        else:
            res.append(num)
            res_set.add(num)
        rem -= 1
        cur += 1
        cur %= N

    print(*res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import *
N,K=map(int,input().split())
A=list(map(int,input().split()))
siz=200814
Y=[[] for i in range(siz)]
p=[]
for i in range(N):
  Y[A[i]].append(i)
  p.append(i)
for i in range(N):
  Y[A[i]].append(N+i)
  p.append(i)
def f(x):
  S=set()
  r=[]
  for i in range(x,N):
    if A[i] in S:
      while True:
        S.discard(r[-1])
        if r[-1]==A[i]:
          del r[-1]
          break
        del r[-1]
    else:
      r.append(A[i])
      S.add(A[i])
  return r

Z=-1
R=0
V=0
while True:
  Z+=1
  V=Y[A[p[Z]]][bisect_right(Y[A[p[Z]]],Z)]
  if V>=N and R==K-1:
    print(*f(Z))
    exit()
  if V>=N:
    R+=1
    V=p[V]
  Z=V
  if Z==N-1:
    K%=(R+1)
    Z=-1
    R=0
    break
if K==0:
  print()
  exit()
while True:
  Z+=1
  V=Y[A[p[Z]]][bisect_right(Y[A[p[Z]]],Z)]
  if V>=N and R==K-1:
    print(*f(Z))
    exit()
  if V>=N:
    R+=1
    V=p[V]
  Z=V

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

import bisect

def main():
	n,k=MI()
	A=LI()
	B=[[] for _ in range(2*10**5+10)]

	for i,v in enumerate(A):
		B[v-1].append(i)

	for li in B:
		if li:
			li.append(li[0])

	#print(A)
	#print(B)

	C=[]

	s=0
	t=-1

	while t<n-1:
		a=A[s]-1
		ti=bisect.bisect_left(B[a][:-1],s)+1
		t=B[a][ti]
		#print(s,t)
		if s>=t:
			C.append(s)
		s=t+1
	#print(C)

	k%=len(C)+1
	#print(k)

	if k==0:
		print()
		exit()

	s=C[k-1]
	#print(s)

	ans=[]

	while s<n:
		a=A[s]-1
		si=bisect.bisect_left(B[a][:-1],s)
		if si+1==len(B[a][:-1]):
			ans.append(a+1)
			s+=1
		else:
			s=B[a][si+1]+1
	print(*ans)



if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
def examA():
    N = DI()/dec(7)
    ans = N
    print(N)
    return

def examB():
    N, K = LI()
    A = LI()
    maxA = max(A)

    def function(s):
        stack = deque()
        num = [0]*(maxA+1)
        for i in range(s,N):
            a = A[i]
            if num[a]==0:
                stack.append(a)
                num[a] += 1
            else:
                while(num[a]>0):
                    num[stack.pop()] -= 1

        return stack

    B = [-1 for _ in range(N)]
    que = {}
    for i in range(N):
        a = A[i]
        if a not in que:
            que[a] = i
        else:
            prev = que.pop(a)
            B[prev] = i - prev
            que[a] = i
    i = 0
    while(que):
        a = A[i]
        if a in que:
            prev = que.pop(a)
            B[prev] = N + i - prev
        i += 1
    #print(B)
    locat_doubling = [[-1]*N for _ in range(51)]

    for i in range(N):
        locat_doubling[0][i] = 0
        locat_doubling[1][i] = B[i] + 1

    for k in range(2,51):
        for i in range(N):
            locat_doubling[k][i] = locat_doubling[k-1][i] + locat_doubling[k-1][(i+locat_doubling[k-1][i])%N]
            if locat_doubling[k][i]>inf:
                locat_doubling[k][i] = inf
    #print(locat_doubling[:5])
    now = 0
    rest = K*N
    for i in range(51)[::-1]:
        if locat_doubling[i][now]<=rest:
            rest -= locat_doubling[i][now]
            now = (locat_doubling[i][now]+now)%N
    #print(rest,now)

    ans = function(now)
    print(" ".join(map(str,ans)))
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""