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: Wrong Answer

Solution code:
def main():

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # open(0).read() is a convenient method:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')

    # ----------------------------------
    # main

    N, K = R()
    A = R()
    X = A * 10
    tmp = 0
    for i, a in enumerate(X):
        if a == tmp:
            tmp = 0
            if (i+1)%N == 0:
                turnaround = (i+1)//N
                K = K % turnaround
                X = A * K
                break
        elif tmp == 0:
            tmp = a
    
    Dic = defaultdict(int)
    i = 0
    ans = []
    for a in X:
        if a in Dic and i >= Dic[a]:
            i = Dic[a]
            if i == 0:
                ans = []
            else:
                ans = ans[:i]
        else:
            ans.append(a)
            Dic[a] = i
            i += 1
    print(*ans)
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # for
    for k, v in Dic.items():
    """

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


resultlist = []

# for i in range(K):
for _ in range(K):
    for i in range(N):
        for j in range(len(s)):
            if A_list[i] == s[j]:
                # print("かぶった")
                s = s[0:j]
                # print(str(i)+" "+str(s))
                break
        else:
            s.append(A_list[i])
            # print(str(i)+" "+str(s))

    # print(str(s))
    for num in range(len(resultlist)):
        if (resultlist[num] == s):
            # print("kabu")
            break
    else:
        resultlist.append(s[:])
        # print(resultlist)

        continue
    break
# print(resultlist)

mod = N % len(resultlist)
# print(resultlist[mod])
ans = ""
for i in resultlist[mod]:
    ans += str(i)+" "

if resultlist[mod]:
    print(ans[:-1])

Submission status: Wrong Answer

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

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

    start = [-1] * N

    start[0] = 1
    pre_index = 0

    val = 0
    ok = False
    while True:
        # print("search", "a[{}]={}".format(pre_index, a[pre_index]))
        for i in range(pre_index + 1, pre_index + N + 2):
            t = i % N
            # print(t)
            if a[pre_index] == a[t]:
                next = (t+1)%N
                tmp = start[pre_index] + i - pre_index + 1
                if start[next] != -1:
                    val = tmp - start[next]
                    ok = True
                    break
                else:
                    # print("next:", next, "tmp:", tmp)
                    start[next] = tmp
                    pre_index = next
                    break
        if ok:
            break
    # print("start:", start)
    # print("val:", val)
    rest = (N * K) % val
    # print("rest:", rest)
    max_ = 0
    ind = 0
    for i in range(N):
        if start[i] > 0:
            if start[i] <= rest:
                if max_ < start[i]:
                    max_ = start[i]
                    ind = i
    ans = []
    rest = rest - start[ind] + 1
    # print("rest: from{}, {} times".format(ind, rest))
    for i in range(rest):
        ans.append(str(a[(ind+i)%N]))
    print(" ".join(ans))



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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(res) in last_results:
        break
    else:
        last_result = res
    last_results.append(tuple(res))
print(" ".join(last_results[(k - last_results.index(tuple(res)) - 1) % len(last_results)]))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect

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

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

memo = [False]*N
memo[0] = True
trace = [0]
cnt = [0]
while True:
    i = trace[-1]
    c = cnt[-1]
    l = indices[A[i]]
    j = (l[bisect(l,i)%len(l)]+1)%N
    if j <= i+1:
        c += 1
    trace.append(j)
    cnt.append(c)
    if memo[j]:
        break
    else:
        memo[j] = True

i = trace.index(trace[-1])

period = cnt[-1] - cnt[i]
K -= 1
if K > cnt[i]:
    K = (K-cnt[i])%period + cnt[i]
head = trace[bisect(cnt, K)-1]

ans = []
cur = head
while cur < N:
    l = indices[A[cur]]
    j = bisect(l, cur)
    if j == len(l):
        ans.append(cur)
        cur += 1
    else:
        cur = l[j]+1

print(*(A[i] for i in ans))

Submission status: Wrong Answer

Solution code:
import math

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

    dp = {}
    memo = set()
    # arrays = []
    if len(set(A)) == len(A):
        if K % 2 == 0:
            print()
        else:
            print(*A, sep=" ")
        return
    
    L = []
    arrays = {}
    # 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(L) == 0:
            s = " "
        else:
            s = " ".join(map(str,L))
        if s in arrays.values():
            loop = len(arrays)
            # print(loop)
            # print(arrays)
            print(arrays[(K-1) % loop])
            return
        else:
            arrays[k] = s



    print(*L, sep=" ")

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
inp = input()
split_inp = inp.split()
N = int(split_inp[0])
K = int(split_inp[1])
inp = input()
a_str_list = inp.split()
a_list = []
for a in a_str_list:
    a_list.append(int(a))

# 初めの入力に対する次の初めの辞書を作る
next_first_dictionary = {}  # 次の終わりと何回目に呼ばれるか
# 0とAの数が最初の数としてあり得る
first_number = 0  # 何もない状態
checking_number = first_number
loop_count = 0
loop_start = 0
loop_time = 0
while True:
    loop_count += 1
    if first_number in next_first_dictionary:
        # この数で始まる時の最後の数は知っている．十分
        loop_start = next_first_dictionary[first_number][1]
        loop_time = loop_count - loop_start
        break
    for a in a_list:
        if first_number == 0:
            first_number = a
        elif a == first_number:
            first_number = 0
    # 残った最初の数がわかる
    next_first_dictionary[checking_number] = [first_number, loop_count]
    checking_number = first_number
# すべての可能性のある始まりにおいての最後の数がわかっている．

# j回繰り返したときに最初にある数を求める
j = K - 1
if j != 0:
    j = j - loop_start
    j = j % loop_time  # ループの中の何番目か
    j += loop_start
after_first_number = -1
for item in next_first_dictionary.values():
    if item[1] == j:
        after_first_number = item[0]
        break
if after_first_number == -1:
    print("Error")
# after first number からはじめる．最後のn回
first_number = after_first_number
s = []
for a in a_list:
    if first_number == 0:
        first_number = a
        s.append(a)
    else:
        if a == first_number:
            s = []
            first_number = 0
        else:
            # すでに同じ数字があるときはそこまでリセットする
            if a in s:
                ind = s.index(a)
                s = s[:ind]
            else:
                s.append(a)
if not s:
    print("")
    exit()
if len(s) == 1:
    print(s[0])
    exit()
print(s[0], end="")
for ans in s[1:]:
    print(" ", end="")
    print(ans, end="")
print("")

Submission status: Wrong Answer

Solution code:
inp = input()
split_inp = inp.split()
N = int(split_inp[0])
K = int(split_inp[1])
inp = input()
a_str_list = inp.split()
a_list = []
for a in a_str_list:
    a_list.append(int(a))

# 初めの入力に対する次の初めの辞書を作る
next_first_dictionary = {}  # 次の終わりと何回目に呼ばれるか
# 0とAの数が最初の数としてあり得る
first_number = 0  # 何もない状態
checking_number = first_number
loop_count = 0
loop_start = 0
loop_time = 0
while True:
    loop_count += 1
    if first_number in next_first_dictionary:
        # この数で始まる時の最後の数は知っている．十分
        loop_start = next_first_dictionary[first_number][1]
        loop_time = loop_count - loop_start
        break
    for a in a_list:
        if first_number == 0:
            first_number = a
        elif a == first_number:
            first_number = 0
    # 残った最初の数がわかる
    next_first_dictionary[checking_number] = [first_number, loop_count]
    checking_number = first_number
# すべての可能性のある始まりにおいての最後の数がわかっている．

# j回繰り返したときに最初にある数を求める
j = K - 1
if j != 0:
    j = j - loop_start
    j = j % loop_time  # ループの中の何番目か
    j += loop_start
after_first_number = -1
for item in next_first_dictionary.values():
    if item[1] == j:
        after_first_number = item[0]
        break
if after_first_number == -1:
    print("Error")
# after first number からはじめる．最後のn回
first_number = after_first_number
s = []
for a in a_list:
    if first_number == 0:
        first_number = a
        s.append(a)
    else:
        if a == first_number:
            s = []
            first_number = 0
        else:
            # すでに同じ数字があるときはそこまでリセットする
            if a in s:
                ind = s.index(a)
                s = s[:ind]
            else:
                s.append(a)
if not s:
    print("")
    exit()
if len(s) == 1:
    print(s)
    exit()
print(s[0], end="")
for ans in s[1:]:
    print(" ", end="")
    print(ans, end="")
print("")

Submission status: Wrong Answer

Solution code:
inp = input()
split_inp = inp.split()
N = int(split_inp[0])
K = int(split_inp[1])
inp = input()
a_str_list = inp.split()
a_list = []
for a in a_str_list:
    a_list.append(int(a))

# 初めの入力に対する次の初めの辞書を作る
next_first_dictionary = {}  # 次の終わりと何回目に呼ばれるか
# 0とAの数が最初の数としてあり得る
first_number = 0  # 何もない状態
checking_number = first_number
loop_count = 0
loop_start = 0
loop_time = 0
while True:
    loop_count += 1
    if first_number in next_first_dictionary:
        # この数で始まる時の最後の数は知っている．十分
        loop_start = next_first_dictionary[first_number][1]
        loop_time = loop_count - loop_start
        break
    for a in a_list:
        if first_number == 0:
            first_number = a
        elif a == first_number:
            first_number = 0
    # 残った最初の数がわかる
    next_first_dictionary[checking_number] = [first_number, loop_count]
    checking_number = first_number
# すべての可能性のある始まりにおいての最後の数がわかっている．

# j回繰り返したときに最初にある数を求める
j = K - 1
if j != 0:
    j = j - loop_start
    j = j % loop_time  # ループの中の何番目か
    j += loop_start
after_first_number = -1
for item in next_first_dictionary.values():
    if item[1] == j:
        after_first_number = item[0]
        break
if after_first_number == -1:
    print("Error")
# after first number からはじめる．最後のn回
first_number = after_first_number
s = []
for a in a_list:
    if first_number == 0:
        first_number = a
        s.append(a)
    else:
        if a == first_number:
            s = []
            first_number = 0
        else:
            # すでに同じ数字があるときはそこまでリセットする
            if a in s:
                ind = s.index(a)
                s = s[:ind]
            else:
                s.append(a)
if not s:
    print("")
    exit()
for ans in s:
    # print(" ", end="")
    print(ans, end=" ")
print("")

Submission status: Wrong Answer

Solution code:
inp = input()
split_inp = inp.split()
N = int(split_inp[0])
K = int(split_inp[1])
inp = input()
a_str_list = inp.split()
a_list = []
for a in a_str_list:
    a_list.append(int(a))

# 初めの入力に対する次の初めの辞書を作る
next_first_dictionary = {}  # 次の終わりと何回目に呼ばれるか
# 0とAの数が最初の数としてあり得る
first_number = 0  # 何もない状態
checking_number = first_number
loop_count = 0
loop_start = 0
loop_time = 0
while True:
    loop_count += 1
    if first_number in next_first_dictionary:
        # この数で始まる時の最後の数は知っている．十分
        loop_start = next_first_dictionary[first_number][1]
        loop_time = loop_count - loop_start
        break
    for a in a_list:
        if first_number == 0:
            first_number = a
        elif a == first_number:
            first_number = 0
    # 残った最初の数がわかる
    next_first_dictionary[checking_number] = [first_number, loop_count]
    checking_number = first_number
# すべての可能性のある始まりにおいての最後の数がわかっている．

# j回繰り返したときに最初にある数を求める
j = K - 1
if j != 0:
    j = j - loop_start
    j = j % loop_time  # ループの中の何番目か
    j += loop_start
after_first_number = -1
for item in next_first_dictionary.values():
    if item[1] == j:
        after_first_number = item[0]
        break
if after_first_number == -1:
    print("Error")
# after first number からはじめる．最後のn回
first_number = after_first_number
s = []
for a in a_list:
    if first_number == 0:
        first_number = a
        s.append(a)
    else:
        if a == first_number:
            s = []
            first_number = 0
        else:
            # すでに同じ数字があるときはそこまでリセットする
            if a in s:
                ind = s.index(a)
                s = s[:ind]
            else:
                s.append(a)
for ans in s:
    # print(" ", end="")
    print(ans, end=" ")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect

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

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

memo = [False]*N
memo[0] = True
trace = [0]
cnt = [0]
while True:
    i = trace[-1]
    c = cnt[-1]
    l = indices[A[i]]
    j = (l[bisect(l,i)%len(l)]+1)%N
    if j <= i+1:
        c += 1
    trace.append(j)
    cnt.append(c)
    if memo[j]:
        break
    else:
        memo[j] = True

i = trace.index(trace[-1])

period = cnt[-1] - cnt[i]
K = (K-cnt[i]-1)%period
head = trace[bisect(cnt, K+cnt[i])-1]

ans = []
cur = head
while cur < N:
    l = indices[A[cur]]
    j = bisect(l, cur)
    if j == len(l):
        ans.append(cur)
        cur += 1
    else:
        cur = l[j]+1

print(*(A[i] for i in ans))

Submission status: Wrong Answer

Solution code:
n, k = list(map(int, input().split()))
a_list = list(map(int,input().split()))
s = []
# kが4以下だった場合
if k <= 4:
    for i in range(k):
        for a in a_list:
            if a in s:
                s = s[:s.index(a)]
            else:
                s.append(a)
else:
    for i in range(k - 4, k):
        for a in a_list:
            if a in s:
                s = s[:s.index(a)]
            else:
                s.append(a)
print(' '.join(map(str, s)))

Submission status: Wrong Answer

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

#print(*range(10000))

def func(L):
  s = []
  for l in L:
    if l in s:
      del s[s.index(l):]
      #s_set.remove(l)
    else:
      s.append(l)
      #s_set.add(l)
  return s

index_dict={}

for i,a in enumerate(A):
  index_dict.setdefault(a,[]).append(i)

#print(index_dict)

from_in_cycle=[]

i = 0
while True:
  a = A[i]
  l = len(index_dict[a])
  j = index_dict[a].index(i)
  if j==l-1:
    from_in_cycle.append(i)
    i = (index_dict[a][0]+1)%N
  else:
    i = (index_dict[a][j+1]+1)%N
  # 循環の評価
  if i==0:
    break
    
#print(from_in_cycle)

if from_in_cycle:
  k = K%(len(from_in_cycle))
  print(*func(A[from_in_cycle[k]:]))
else:
  print('')

Submission status: Wrong Answer

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


pair2idx = {tuple(): 0}

rest = tuple()
cnt = 0
while True:
  rest = rest + A
  idx = 0;
  for i in range(len(rest)):
    if idx >= len(rest):
      break
    try:
      next_idx = rest.index(rest[idx], idx + 1)
      rest = rest[:idx] + rest[next_idx + 1:]
    except ValueError:
      idx += 1
  if rest in pair2idx:
    break
  else:
    cnt += 1
    pair2idx[rest] = cnt

target = K % (cnt + 1)
print(*list(pair2idx.keys())[target])

Submission status: Wrong Answer

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]
        else:
            s.append(a[j])
    if len(s) == 0:
        if i == 0:
            break
        else:
            i=(k+1)/(i+1)*(i+1)
    else:
        i+=1


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

Submission status: Wrong Answer

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(2):
    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: Wrong Answer

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の添字で、最後にvisitしたときを持つ。visit = （そこからスタート！）

NK = N * K
visited = [None] * N
x = 0
visited[0] = 0
while True:
    y = next_cycle_start[x % N] + (x//N) * N
    if y >= NK:
        break
    if visited[y % N] is not None:
        # 周期が見つかった！
        P = y - visited[y % N]
        y += (NK - y) // P * P
        x = y
        break
    else:
        visited[y % N] = y
        x = y

answer = []
while x < NK:
    y = next_cycle_start[x % N] + (x//N) * N
    if y > NK:
        answer.append(A[x%N])
        x += 1
        continue
    x = y

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

Submission status: Wrong Answer

Solution code:
import math

def main():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    
    if len(A) > 2:
        if A[-2] == A[-1]:
            print()
            return 

    dp = {}
    memo = set()
    
    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)}

    print(*L, sep=" ")

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import math

def main():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    
    X = A * 2
    dp = {}
    memo = set()
    
    # print(X)
    
    L = [A[0]]
    dp[X[0]] = 0
    memo = set([X[0]])

    for a in X[1:]:
        # 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)}

    print(*L, sep=" ")

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k=[int(i) for i in input().split()]
index=(n-1)%k

s=input().split()
s=s[index:]
print(" ".join(s))

Submission status: Wrong Answer

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

for i in range(min(2,k)):
#    print "i="+str(i)
    for j in range(n):
#        print "j="+str(j)
        if a[j] in s:
            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

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