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:
from bisect import bisect_right as bisect
N, K = map(int, input().split())
A = list(map(int, input().split()))
m = max(A)
a_to_i = [[] for _ in range(m+1)]
for i in range(N):
    a_to_i[A[i]].append(i)
now = 0
next_k_i = [[None]*N for _ in range(30)]
for now in range(N):
    h = 0
    i = bisect(a_to_i[A[now]], now)
    if i == len(a_to_i[A[now]]):
        i = 0
        h+=N
    i = a_to_i[A[now]][i]
    h+=(i-now+1)
    next_k_i[1][now] = ((i+1)%N, h)
for i in range(2, 30):
    for j in range(N):
        a, b = next_k_i[i-1][j]
        c, d = next_k_i[i-1][a]
        next_k_i[i][j] = (c, b+d)
now = 0
cnt = K*N
while cnt:
    flag = False
    for i in range(1, 30)[::-1]:
        a, b = next_k_i[i][now]
        if cnt>=b:
            cnt-=b
            now = a
            flag = True
            break
    if not flag:
        break
ans = []
while now<N:
    a = next_k_i[1][now][0]
    if next_k_i[1][now][0] == 0:
        a+=N
    if a>now+1:
        now = a
        continue
    ans.append(A[now])
    now+=1
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
mi = lambda: map(int, input().split())
e = enumerate
n,k = mi()
m = (n+k).bit_length()
a = list(mi())
g = [None]*n

d = dict()
for i,x in e(a):
  d[x] = i
for i,x in e(a):
  g[d[x]] = ((i+1)%n,int(d[x]>=i)+int(i+1==n))
  d[x] = i
db = [g]
for _ in range(m):
  old = db[-1]
  new = [None]*n
  for i in range(n):
    p,q = old[i]
    r,s = old[p]
    new[i] = (r,q+s)
  db.append(new)
cur = 0
st = m
cs = 0
while st>=0:
  p,q = db[st][cur]
  if cs+q < k:
    cs += q
    cur = p
  else:
    st -= 1
    
q = list()
while cur < n:
  if g[cur][1] == 0:
    cur = g[cur][0]
  elif g[cur] == (0,1):
    break
  else:
    q.append(a[cur])
    cur += 1
  
print(' '.join(map(str,q)))

Submission status: Time Limit Exceeded

Solution code:
mi = lambda: map(int, input().split())
e = enumerate
n,k = mi()
m = (n+k).bit_length()
a = list(mi())
g = [None]*n

d = dict()
for i,x in e(a):
  d[x] = i
for i,x in e(a):
  g[d[x]] = ((i+1)%n,int(d[x]>=i)+int(i+1==n))
  d[x] = i
db = [g]
for _ in range(m):
  old = db[-1]
  new = [None]*n
  for i in range(n):
    p,q = old[i]
    r,s = old[p]
    new[i] = (r,q+s)
  db.append(new)
cur = 0
st = m
cs = 0
while st>=0:
  p,q = db[st][cur]
  if cs+q < k:
    cs += q
    cur = p
  else:
    st -= 1
q = list()
for x in a[cur:]:
  if x in q:
    t = x-1
    while t != x:
      t = q.pop()
  else:
    q.append(x)
print(' '.join(map(str,q)))

Submission status: Time Limit Exceeded

Solution code:
mi = lambda: map(int, input().split())
e = enumerate
n,k = mi()
a = list(mi())
g = [None]*n

d = dict()
for i,x in e(a):
  d[x] = i
for i,x in e(a):
  g[d[x]] = ((i+1)%n,int(d[x]>=i)+int(i+1==n))
  d[x] = i
db = [g]
for _ in range(100):
  old = db[-1]
  new = [None]*n
  for i in range(n):
    p,q = old[i]
    r,s = old[p]
    new[i] = (r,q+s)
  db.append(new)
cur = 0
st = 100
cs = 0
while st>=0:
  p,q = db[st][cur]
  if cs+q < k:
    cs += q
    cur = p
  else:
    st -= 1
q = list()
for x in a[cur:]:
  if x in q:
    t = x-1
    while t != x:
      t = q.pop()
  else:
    q.append(x)
print(' '.join(map(str,q)))

Submission status: Time Limit Exceeded

Solution code:
mi = lambda: map(int, input().split())
e = enumerate
n,k = mi()
a = list(mi())
g = [None]*n

d = dict()
for i,x in e(a):
  d[x] = i
for i,x in e(a):
  g[d[x]] = ((i+1)%n,int(d[x]>=i)+int(i+1==n))
  d[x] = i
db = [g]
for _ in range(40):
  old = db[-1]
  new = [None]*n
  for i in range(n):
    p,q = old[i]
    r,s = old[p]
    new[i] = (r,q+s)
  db.append(new)
cur = 0
st = 40
cs = 0
while st>=0:
  p,q = db[st][cur]
  if cs+q < k:
    cs += q
    cur = p
  else:
    st -= 1
q = list()
for x in a[cur:]:
  if x in q:
    t = x-1
    while t != x:
      t = q.pop()
  else:
    q.append(x)
print(' '.join(map(str,q)))

Submission status: Time Limit Exceeded

Solution code:
mi = lambda: map(int, input().split())
e = enumerate
n,k = mi()
a = list(mi())
g = [None]*n

d = dict()
for i,x in e(a):
  d[x] = i
for i,x in e(a):
  g[d[x]] = ((i+1)%n,int(d[x]>=i)+int(i+1==n))
  d[x] = i
db = [g]
for _ in range(30):
  old = db[-1]
  new = [None]*n
  for i in range(n):
    p,q = old[i]
    r,s = old[p]
    new[i] = (r,q+s)
  db.append(new)
cur = 0
st = 30
cs = 0
while st>=0:
  p,q = db[st][cur]
  if cs+q < k:
    cs += q
    cur = p
  else:
    st -= 1
q = list()
for x in a[cur:]:
  if x in q:
    t = x-1
    while t != x:
      t = q.pop()
  else:
    q.append(x)
print(' '.join(map(str,q)))

Submission status: Time Limit Exceeded

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

def getDistNexts(As):
    lenA = len(As)
    poss = dict()
    for i, A in enumerate(As):
        if A not in poss:
            poss[A] = i + lenA

    distNexts = [0]*(lenA)
    for i in reversed(range(lenA)):
        distNexts[i] = poss[As[i]] - i
        poss[As[i]] = i
    return distNexts

distNexts = getDistNexts(As)

maxD = (N*K).bit_length() - 1

dp = [[0]*(N) for _ in range(maxD+1)]
for i in range(N):
    dp[0][i] = distNexts[i] + 1
for d in range(1, maxD+1):
    for i in range(N):
        i2 = i + dp[d-1][i]
        dp[d][i] = i2 + dp[d-1][i2%N] - i

iNow = 0
dist = 0
for d in reversed(range(maxD+1)):
    if dist+dp[d][iNow] <= N*K-1:
        dist += dp[d][iNow]
        iNow = dist%N

Ss = []
setS = set()
for A in As[iNow:]:
    if A in setS:
        S = ''
        while S != A:
            S = Ss.pop()
            setS.remove(S)
    else:
        Ss.append(A)
        setS.add(A)

if Ss:
    print(' '.join(map(str, Ss)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, K = map(int, input().split())
A = list(map(int, input().split()))
next_step = [0] * N
memo = [-1] * (2*10**5)
cnt = 0
for i, a in enumerate(A+A):
    if memo[a-1] >= 0:
        if next_step[memo[a-1]%N]:
            continue
        next_step[memo[a-1]] = i - memo[a-1] + 1
        cnt += 1
    if cnt == N:
        break
    memo[a-1] = i

j = 0
while True:
    if j + next_step[j%N] < N*K:
        j += next_step[j%N]
        if j%N == 0:
            j = max(j, N*K//j*j)
    else:
        break

q = deque()
for k in range(j, N*K):
    a = A[k%N]
    if a not in q:
        q.append(a)
    else:
        while a in q:
            q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, K = map(int, input().split())
A = list(map(int, input().split()))
next_step = [0] * N
memo = dict()
cnt = 0
for i, a in enumerate(A+A):
    if a in memo.keys():
        if next_step[memo[a]%N]:
            continue
        next_step[memo[a]] = i - memo[a] + 1
        cnt += 1
    memo[a] = i

j = 0
while True:
    if j + next_step[j%N] < N*K:
        j += next_step[j%N]
        if j%N == 0:
            j = max(j, N*K//j*j)
    else:
        break

q = deque()
for k in range(j, N*K):
    a = A[k%N]
    if a not in q:
        q.append(a)
    else:
        while a in q:
            q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(pow(10, 6))

def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    na = [-1 for _ in range(2*n)]
    nk = n * k

    prevai = {}
    for i, _a in enumerate(a+a):
        if _a in prevai:
            na[prevai[_a]] = (i-prevai[_a])%n + 1
            if na[prevai[_a]] == 1:
                na[prevai[_a]] = n+1
        prevai[_a] = i

    doubling = [[0 for _ in range(n)] for _ in range(61)]
    for i in range(n):
        doubling[0][i] = na[i]
    for i in range(1, 61):
        for j in range(n):
            doubling[i][j] = doubling[i-1][j] + doubling[i-1][(j+doubling[i-1][j])%n]

    tmp = 0
    for i in range(60, -1, -1):
        if nk - tmp >= doubling[i][tmp%n]:
            tmp += doubling[i][tmp%n]

    if tmp == nk:
        return
    
    ans  = []
    adict = {}
    for i in range(tmp%n, n):
        if a[i] in adict and adict[a[i]] > 0:
            while True:
                _a = ans.pop()
                adict[_a] = 0
                if _a == a[i]:
                    break
        else:
            ans.append(a[i])
            adict[a[i]] = 1
    print(*ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
A = LIST()

# 各値毎の出現位置
B = [[] for i in range(max(A)+1)]
for i, a in enumerate(A+A):
    B[a].append(i)
# 同値が何個先で出現するかを保持する
C = [0] * N
for li in B:
    for i in range(len(li)-1):
        if li[i] >= N:
            break
        C[li[i]] = li[i+1] - li[i]

# nxt[k][i] := iからスタートして、2^kブロック移動後の現在位置
nxt = list2d(61, N, 0)
# 初期化
for i in range(N):
    # iからのスタートは、1(2^0)回目はC[i]+1先に進む
    nxt[0][i] = C[i] + 1
# ダブリングのテーブル構築
for k in range(1, 61):
    for i in range(N):
        nxt[k][i] = nxt[k-1][i] + nxt[k-1][(i+nxt[k-1][i])%N]

# N*K以内でギリギリまで現在位置を進める
def get_cur():
    i = cur = 0
    while True:
        for k in range(61):
            if cur + nxt[k][i] > N * K:
                if k != 0:
                    cur += nxt[k-1][i]
                    i = cur % N
                    break
                else:
                    return cur
cur = get_cur()

# 最後のブロックについてシミュレーションする
ans = []
s = set()
for i in range(cur, N*K):
    a = A[i%N]
    # 追加
    if a not in s:
        ans.append(a)
        s.add(a)
    # 削除
    else:
        while True:
            key = ans.pop()
            s.remove(key)
            if key == a:
                break
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import collections


def main():
    N, K = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]
    to_next = [0] * N

    occs = collections.defaultdict(list)

    for i, a in enumerate(A):
        occs[a].append(i)
        if len(occs[a]) > 1:
            to_next[occs[a][-2]] = i - occs[a][-2] + 1

    for i, a in enumerate(A):
        to_next[occs[a][-1]] = N - occs[a][-1] + occs[a][0] + 1

    pos = 0
    ops = 0
    first_visit = [-1] * N

    while first_visit[pos] == -1 and ops + to_next[pos] < N * K:
        first_visit[pos] = ops
        ops += to_next[pos]
        pos = (pos + to_next[pos]) % N

    if first_visit[pos] != -1:
        rem_ops = (N * K - ops) % (ops - first_visit[pos])
        # ops += (N * K - ops) // (ops - first_visit[ops])

    else:
        rem_ops = N * K - ops

    sol = []
    contains = set()

    for i in range(rem_ops):
        a = A[(pos + i) % N]
        if a in contains:
            x = sol.pop()
            while x != a:
                contains.remove(x)
                x = sol.pop()
            contains.remove(x)
        else:
            contains.add(a)
            sol.append(a)

    print(' '.join(str(x) for x in sol))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
	input = sys.stdin.readline
	n,k = map(int,input().split())

	aa = [int(item) for item in input().split()]
	p=[-1]*200001
	b=[0]*n
	bl=0
	
	m=[]
	
	while True:
		for i, a in enumerate(aa):
			if p[a]>=0:
				x=p[a]
				for j in range(x,bl):
					p[b[j]]=-1
				bl=x
			else:
				b[bl]=a
				p[a]=bl
				bl+=1
		m.append(b[0:bl])
		if bl==0 or len(m)>=k:
			break;
	
	print(*m[(k-1)%len(m)])
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
	input = sys.stdin.readline
	n,k = map(int,input().split())

	aa = [int(item) for item in input().split()]
	p=[-1]*200001
	b=[0]*n
	bl=0
	
	m=[]
	
	while True:
		for i, a in enumerate(aa):
			if p[a]>=0:
				x=p[a]
				for j in range(x,bl):
					p[b[j]]=-1
				bl=x
			else:
				b[bl]=a
				p[a]=bl
				bl+=1
		m.append(b[0:bl])
		if bl==0:
			break;
	
	print(*m[(k-1)%len(m)])
main()

Submission status: Time Limit Exceeded

Solution code:
def p_b():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    S = []
    ans = []

    for n in range(K):
        for i in range(N):
            if A[i] in S:
                while S and S.pop() != A[i]:
                    pass
            else:
                S.append(A[i])

        ans.append(S.copy())
        if not S:
            break

    print(" ".join(map(str, ans[(K - 1) % len(ans)])))


if __name__ == '__main__':
    p_b()

Submission status: Time Limit Exceeded

Solution code:
import copy
n, k=map(int, input().split())
a=list(map(int, input().split()))

lo=[]
val=[]
for i in range(k):
    for j in a:
        #print(val)
        if j in val:
            while j in val:
                val.pop(-1)
        else:
            val.append(j)
        
        #print(val)
    
    if val in lo:
        break
    lo.append(copy.copy(val))
    #print(lo)

print(" ".join(map(str, lo[(k-1)%len(lo)])))

Submission status: Time Limit Exceeded

Solution code:
n,k = list(map(int, input().split()))
al = list(map(int,input().split()))
s = []
l=[]
x=0
while x<=n:
    for j in al:
        if j not in s:
            s.append(j)
        else:
            s=s[:s.index(j)]
    if s in l:        
        break
    l.append(s.copy())
    x+=1
#print(k,len(l))
print(*l[k%len(l)-1])

Submission status: Time Limit Exceeded

Solution code:
n,k = list(map(int, input().split()))
al = list(map(int,input().split()))
s = []
l=[]
while True:
    for j in al:
        if j not in s:
            s.append(j)
        else:
            s=s[:s.index(j)]
    if s in l:        
        break
    l.append(s.copy())
#print(k,len(l))
print(*l[k%len(l)-1])

Submission status: Time Limit Exceeded

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

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

def print_ans(s):
    if len(s)==0:
        print()
    else:
        ans = str(s[0])
        for val in s[1:]:
            ans = ans + " {}".format(val)
        print(ans)

s = []
count = 0
flag = True
done_list = [[]]
while(flag):
    count += 1
    for a in a_list:
        if a in s:
            s = s[0:s.index(a)]
        else:
            s.append(a)

    if count == k:
        print_ans(s)
        exit()

    if s in done_list:
        flag = False
    else:
        done_list.append(s.copy())


loop_num = len(done_list)
s = done_list[ k % loop_num ]
print_ans(s)

Submission status: Time Limit Exceeded

Solution code:
import copy

n,k = map(int, input().split())
a = []
a = list(map(int, input().split()))
count = 0
list = []
cycle = []

while True :
  cycle.append(copy.deepcopy(list))
  count = count + 1
    
  for i in range(len(a)) :
    if list.count(a[i]) == 0 :
  	  list.append(a[i])
    else :
      list = list[0:list.index(a[i])]
           
  if len(list) == 0 :
    break
       
for i in range(len(cycle[k % count])) :
  print(cycle[k % count][i], end = ' ')

Submission status: Time Limit Exceeded

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

table = {}
init_table = {}
move = {}

for i in range(N):
    if A[i] in table:
        move[table[A[i]]], move[i] = i+1, init_table[A[i]]+1
    else:
        if A[i] not in init_table:
            init_table[A[i]] = i
    table[A[i]] = i

T = K
next_idx = 0
remain = [0]
for i in range(1, K+1):
    idx = next_idx
    while idx in move and idx < move[idx]:
        idx = move[idx]
    remain.append(idx)
    if idx in move:
        next_idx = move[idx]
    else:
        next_idx += 1
    if(idx == N and i != K):
        T = K % i
        break

if(T == 0):
    print()
    exit()
idx = remain[T]
ret = []
while idx < len(A):
    while idx in move and idx < move[idx]:
        idx = move[idx]
    if(idx >= len(A)):
        break
    ret.append(A[idx])
    idx += 1

print(*ret)

Submission status: Time Limit Exceeded

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

table = {}
init_table = {}
move = {}

for i in range(N):
    if A[i] in table:
        move[table[A[i]]], move[i] = i+1, init_table[A[i]]+1
    else:
        if A[i] not in init_table:
            init_table[A[i]] = i
    table[A[i]] = i

T = K
next_idx = 0
remain = {}
for i in range(1, K+1):
    idx = next_idx
    while idx in move and idx < move[idx]:
        idx = move[idx]
    remain[i] = idx
    if idx in move:
        next_idx = move[idx]
    else:
        next_idx += 1
    if(idx == N and i != K):
        T = K % i
        break

if(T == 0):
    print()
    exit()
idx = remain[T]
ret = []
while idx < len(A):
    while idx in move and idx < move[idx]:
        idx = move[idx]
    if(idx >= len(A)):
        break
    ret.append(A[idx])
    idx += 1

print(*ret)

Submission status: Time Limit Exceeded

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

for i in range(N*K):
    j = i % N
    if (A[j] in s):
        d = s.index(A[j])
        del s[d:]

    else:
        s.append(A[j])

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

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
arr = [int(c) for c in input().split()]

s = []
s_after_iter = [s[:]]
k = 0
index_map = {}
while k < K:
    for a in arr:
        if a in index_map:
            index = index_map[a]
            for i in s[index:]:
                del index_map[i]
            s = s[:index]
        else:
            s.append(a)
            index_map[a] = len(s) - 1

    if len(s) == 0:
        break

    s_after_iter.append(s[:])
    k += 1

print(' '.join(map(str, s_after_iter[K % len(s_after_iter) if k < K else k])))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
arr = [int(c) for c in input().split()]

s = []
s_after_iter = [s[:]]
k = 0
while k < K:
    for a in arr:
        i = len(s) - 1
        while i > -1:
            if s[i] == a:
                break
            i -= 1
        
        if i == -1:
            s.append(a)
        else:
            s = s[:i]

    if len(s) == 0:
        break

    s_after_iter.append(s[:])
    k += 1

print(' '.join(map(str, s_after_iter[K % len(s_after_iter) if k < K else k])))

Submission status: Time Limit Exceeded

Solution code:
def step(s,i):
    if i in s:
        return s[:s.index(i):]
    else:
        return s+[i]

N,K=[int(i) for i in input().split(" ")]
A=[int(j) for j in input().split(" ")]

s=[]
log=[]

loop=K
for i in range(K):
    for a in A:
        s=step(s,a)
    log.append(s)
    if len(s)!=0:
        continue
    else:
        loop=i
        break

print(" ".join([str(c) for c in log[K%(loop+1)-1]]))

Submission status: Time Limit Exceeded

Solution code:
def step(s,i):
    if i in s:
        return s[:s.index(i):]
    else:
        return s+[i]

N,K=[int(i) for i in input().split(" ")]
A=[int(j) for j in input().split(" ")]

s=[]

loop=K
for i in range(K):
    for a in A:
        s=step(s,a)
    if len(s)!=0:
        continue
    else:
        loop=i
        break

s=[]
for i in range(K%(loop+1)):
    for a in A:
        s=step(s, a)

print(" ".join([str(c) for c in s]))

Submission status: Time Limit Exceeded

Solution code:
import math

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

M=N*K

logNK=math.floor(math.log2(N*K))
if logNK==0 :
    logNK=1
f=([[0]*N for i in range(logNK)])

#calc f0(n)
idx=[[] for i in range(200001)]
for i, a in enumerate(A):
    idx[a].append(i)


for i, a in enumerate(A):
    l=idx[a]
    n=l.index(i)
    if n+1 == len(l):
        j = N + l[0]
    else:
        j = l[n+1]
    f[0][i]=j-i+1


for k in range(1,logNK):
    for i in range(N):
        f[k][i]=f[k-1][ i ] + f[ k-1 ][(i + f[k-1][i])%N ]

#step2
n=0
for k in range(logNK-1,0,-1):
    i=n%N
    if n + f[k][i] < M:
        n+=f[k][i]

#step3
tmp=[]
for i in range(n,M):
    imodn=i%N
    if A[imodn] in tmp:
        tmp=tmp[0:tmp.index(A[imodn])]
    else:
        tmp.append(A[imodn])

print(' '.join(map(str,tmp)))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
As = list(map(int, input().split()))
M = [[] for i in range(200001)]
for i, a in enumerate(As):
  M[a].append(i)
S = []
for i, a in enumerate(As):
  l = M[a]
  index = l.index(i)
  if index+1 == len(l):
    n = l[0]+N
  else:
    n = l[index+1]
  S.append(n+1-i)
#print(S)
p = 0
while True:
  p = p+S[p%N]
  if p%N == 0:
    break
count = p//N
#print(count)
K = K%count
#print(K)
p = 0
while True:
  q = p+S[p%N]
  if q > N*K:
    break
  p = q
index = p%N
#print(index, As[index:N])
s = []
for a in As[index:N]:
  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:
N, K = map(int, input().split())
As = list(map(int, input().split()))
M = [[] for i in range(200001)]
for i, a in enumerate(As):
  M[a].append(i)
S = []
for i, a in enumerate(As):
  l = M[a]
  index = l.index(i)
  if index+1 == len(l):
    n = l[0]+N+1
  else:
    n = l[index+1]+1
  S.append((n//N, n%N))
#print(S)
count = 0
p = 0
while True:
  c, p = S[p]
  count += c
  if p == 0:
    break
#print(count)
K = K%count
#print(K)
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

'''
9 4
1 8 6 6 8 7 8 1 9
'''

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

last = dict()
v = [-1] * N

for i, a in enumerate(A + A) :
    if a in last and last[a] < N :
        v[last[a]] = i + 1
    
    last[a] = i

dist = [-1] * N
cur = 0
s = 0
while dist[cur] < 0 :
    dist[cur] = s 
    s += v[cur] - cur
    cur = v[cur] % N

# d1 - ループに入るまでの長さ, d2 - ループの長さ
d1 = dist[cur]
d2 = s - d1
NK = N * K

if NK > d1 :
    m = (NK-d1) % d2
    cur = v[cur] % N
    s = 0
    while m > dist[cur] - d1 > 0 :
        s = dist[cur] - d1
        cur = v[cur] % N
    m -= s
else :
    m = N

ret = []
if m != 0 :
    last = dict()
    for a in A[-m:] :
        if a in ret :
            ret = ret[:ret.index(a)]
        else :
            ret.append(a)
        
print(' '.join([str(i) for i in ret]))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

def f(n, k):
    aa = list(map(int, input().split()))
    idx = defaultdict(list)
    to = [-1] * n
    for i, a in enumerate(aa):
        idx[a].append(i)
    for ik in idx.values():
        for i in range(len(ik)):
            to[ik[i - 1]] = ik[i]
    start = []
    ds = []
    i = 0
    # print(idx)
    # print(to)
    while 1:
        ni = (to[i] + 1) % n
        d = (ni - i) % n
        if d == 1:
            d += n
        ds.append(d)
        start.append(i)
        if ni == 0: break
        i = ni
    alld = sum(ds)
    if alld == 0:
        if k * n % 2:
            print(aa[0])
        else:
            print()
        exit()
    m = k * n % alld
    s = 0
    for i, d in enumerate(ds):
        s += d
        if s > m:
            s -= d
            break
    mm = m - s
    # print(start)
    # print(ds)
    # print(m,mm)
    i = start[i]
    s = []
    for ii in range(i, i + mm):
        if aa[ii] in s:
            i = s.index(aa[ii])
            s = s[:i]
        else:
            s += [aa[ii]]
    print(*s)

n, k = map(int, input().split())
f(n, k)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n, k = map(int, input().split())
aa = list(map(int, input().split()))
idx = defaultdict(list)
to = [-1]*n
for i, a in enumerate(aa):
    idx[a].append(i)
for ik in idx.values():
    for i in range(len(ik)):
        to[ik[i - 1]] = ik[i]
start = []
ds=[]
i = 0
#print(idx)
#print(to)
while 1:
    ni = (to[i] + 1) % n
    d=(ni - i) % n
    if d==1:
        d+=n
    ds.append(d)
    start.append(i)
    if ni == 0: break
    i=ni
alld=sum(ds)
if alld==0:
    if k*n%2:
        print(aa[0])
    else:
        print()
    exit()
m=k*n%alld
s=0
for i,d in enumerate(ds):
    s+=d
    if s>m:
        s-=d
        break
mm=m-s
#print(start)
#print(ds)
#print(m,mm)
i=start[i]
s=[]
for ii in range(i,i+mm):
    if aa[ii] in s:
        i = s.index(aa[ii])
        s = s[:i]
    else:
        s += [aa[ii]]
print(*s)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
A = [int(i) for i in input().split()]

dist = dict()
i = 0
s = 0
while True :
    cur = i % N
    if cur in dist :
        d1 = dist[cur][1]
        d2 = i - d1
        break
    
    i += 1
    while A[i%N] != A[cur] :
        i += 1
    
    i += 1
    dist[cur] = (i%N, s)
    s = i

if N*K > d1 :
    m = (N*K - d1) % d2
    while m > dist[dist[cur][0]][1] - d1 :
        cur = dist[cur][0]
    m -= dist[cur][1] - d1
else :
    m = 0
  
ret = []
for a in A[-m:] :
    if a in ret :
        ret = ret[:ret.index(a)]
    else :
        ret.append(a)
        
print(' '.join([str(i) for i in ret]))

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
aa=list(map(int,input().split()))
s=[]
cnt=0
ans=[[]]
for _ in range(k):
    for a in aa:
        cnt+=1
        if a in s:
            i=s.index(a)
            s=s[:i]
        else:
            s+=[a]
        ans.append(tuple(s))
    if not s:
        if not cnt % n:
            m = (k * n) % cnt
            print(*ans[m])
            break
else:
    print(*ans[-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import os
import copy


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

    a = []
    k = 0
    while pow(2, k) < N * K:
        ak = []

        if k == 0:
            for i in range(N):
                for j in range(1, N+1):
                    if(A[i] == A[(i+j) % N]):
                        width = j + 1
                        break
                ak.append(width)
        else:
            for i in range(N):
                step1 = a[k-1][i]
                step2 = a[k-1][(i + step1) % N]
                width = step1 + step2
                ak.append(width)

        a.append(ak)
        if a[k][0] > N * K:
            break
        k += 1

    now = 0
    for e in range(k)[::-1]:
        if now + a[e][now % N] > N*K:
            continue
        now = now + a[e][now % N]

    # print(now)

    S = []
    for i in range(now, N*K):
        if A[i % N] not in S:
            S.append(A[i % N])
        else:
            for j in range(len(S)):
                if(S[j] == A[i % N]):
                    S = S[:j]
                    break

    print(' '.join(map(str, S)))


solve()

# test_path = 'test_case'
# FILES = os.listdir(test_path)
# print('test case => %s\n**********' % FILES)
# for FILE in FILES:
#     fdr = os.open(test_path + '/' + FILE, os.O_RDONLY)
#     print("\ncase : %s" % FILE)
#     os.dup2(fdr, sys.stdin.fileno())
#     solve()

# print("\n**********\nfinish")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import os
import copy


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

    s_set = []
    count = 0
    s = []

    a = []
    k = 0
    while pow(2, k) < N * K:
        ak = []

        if k == 0:
            for i in range(N):
                for j in range(1, N+1):
                    if(A[i] == A[(i+j) % N]):
                        width = j + 1
                        break
                ak.append(width)
        else:
            for i in range(N):
                step1 = a[k-1][i]
                step2 = a[k-1][(i + step1) % N]
                width = step1 + step2
                ak.append(width)

        a.append(ak)
        k += 1

    now = 0
    for e in range(k)[::-1]:
        if now + a[e][now % N] > N*K:
            continue
        now = now + a[e][now % N]

    # print(now)

    S = []
    for i in range(now, N*K):
        if A[i % N] not in S:
            S.append(A[i % N])
        else:
            for j in range(len(S)):
                if(S[j] == A[i % N]):
                    S = S[:j]
                    break

    print(' '.join(map(str, S)))


solve()

# test_path = 'test_case'
# FILES = os.listdir(test_path)
# print('test case => %s\n**********' % FILES)
# for FILE in FILES:
#     fdr = os.open(test_path + '/' + FILE, os.O_RDONLY)
#     print("\ncase : %s" % FILE)
#     os.dup2(fdr, sys.stdin.fileno())
#     solve()

# print("\n**********\nfinish")

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
A = [int(i) for i in input().split()]

rlist = []
i = 0
while True :
    cur = i
    i += 1
    while A[i%N] != A[cur%N] :
        i += 1
    rlist.append(i-cur+1)
    if i % N == N - 1 :
        break
    i += 1

s = sum(rlist) 
m = N*K%s

ss = 0
for r in rlist :
    if ss + r < m :
        ss += r
    else :
        break     

ret = []
for a in A[ss % N:] :
    if not a in ret :
        ret.append(a)
    else :
        ret = ret[:ret.index(a)]
        
print(' '.join([str(i) for i in ret]))