Playlist (Codeforces 1484D)
Tags: Implement, dsu

Arkady has a playlist that initially consists of $$$n$$$ songs, numerated from $$$1$$$ to $$$n$$$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $$$1$$$. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the beginning.Each song has a genre $$$a_i$$$, which is a positive integer. Let Arkady finish listening to a song with genre $$$y$$$, and the genre of the next-to-last listened song be $$$x$$$. If $$$\operatorname{gcd}(x, y) = 1$$$, he deletes the last listened song (with genre $$$y$$$) from the playlist. After that he continues listening normally, skipping the deleted songs, and forgetting about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately.Here $$$\operatorname{gcd}(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.For example, if the initial songs' genres were $$$[5, 9, 2, 10, 15]$$$, then the playlist is converted as follows: [5, 9, 2, 10, 15] $$$\to$$$ [5, 9, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] (because $$$\operatorname{gcd}(5, 9) = 1$$$) $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 10, 15] (because $$$\operatorname{gcd}(5, 2) = 1$$$) $$$\to$$$ [5, 10, 15] $$$\to$$$ [5, 10, 15] $$$\to$$$ ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs.Given the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows.The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of songs.The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the genres of the songs.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output: For each test case, print a single line. First, print a single integer $$$k$$$ — the number of deleted songs. After that print $$$k$$$ distinct integers: deleted songs in the order of their deletion.

Note: Explanation of the first test case is given in the statement.In the second test case, the playlist is converted as follows: [1, 2, 4, 2, 4, 2] $$$\to$$$ [1, 2, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] (because $$$\operatorname{gcd}(1, 2) = 1$$$) $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [4, 2, 4, 2] (because $$$\operatorname{gcd}(2, 1) = 1$$$) $$$\to$$$ [4, 2, 4, 2] $$$\to$$$ ...In the third test case, the playlist is converted as follows: [1, 2] $$$\to$$$ [1, 2] $$$\to$$$ [1] (because $$$\operatorname{gcd}(1, 2) = 1$$$) $$$\to$$$ [1] $$$\to$$$ [1] (Arkady listened to the same song twice in a row) $$$\to$$$ [] (because $$$\operatorname{gcd}(1, 1) = 1$$$).The fourth test case is same as the third after deletion of the second song.In the fifth test case, the same song is listened to over and over again, but since $$$\operatorname{gcd}(2, 2) \ne 1$$$, it is not deleted.

Sample Inputs:
5
5
5 9 2 10 15
6
1 2 4 2 4 2
2
1 2
1
1
1
2

Sample Outputs:
2 2 3 
2 2 1 
2 2 1 
1 1 
0

Solution (Python):
import math

def solve(genres):
    deleted_set = [False] * len(genres)
    deleted_orders = []
    next_indices = [i + 1 if i + 1 < len(genres) else 0 for i in range(len(genres))]
    gcd1_pairs = []
    for i in range(len(genres)):
        gcd = math.gcd(genres[i], genres[next_indices[i]])
        if gcd == 1:
            gcd1_pairs.append((i, next_indices[i]))
    i = 0
    while i < len(gcd1_pairs):
        pair = gcd1_pairs[i]
        first_index = pair[0]
        second_index = pair[1]
        if deleted_set[first_index] or deleted_set[second_index]:
            i += 1
            continue
        deleted_orders.append(second_index)
        deleted_set[second_index] = True
        next_indices[first_index] = next_indices[second_index]
        gcd = math.gcd(genres[first_index], genres[next_indices[first_index]])
        if gcd == 1:
            gcd1_pairs.append((first_index, next_indices[first_index]))
        i += 1
    return deleted_orders

def run():
    t = int(input())
    for i in range(t):
        _n = int(input())
        genres = list(map(int, input().split()))
        deleted_orders = solve(genres)
        result = [str(len(deleted_orders))]
        for index in deleted_orders:
            result.append(str(index + 1))
        print(' '.join(result))
run()

Solution (Python):
t = int(input())

def euclidean(a, b):
    (a, b) = (max(a, b), min(a, b))
    while b:
        (a, b) = (b, a % b)
    return a

def main():
    n = int(input())
    l = [int(s) for s in input().split()]
    l_next = list(range(1, n)) + [0]
    l_forw = list(range(1, n)) + [0]
    prev = n - 1
    i = 0
    res = []
    while True:
        if l_forw[i] == i:
            if l[i] == 1:
                res.append(i + 1)
            break
        if euclidean(l[i], l[l_forw[i]]) == 1:
            if l_forw[i] == l_next[i]:
                l_next[i] = l_next[l_next[i]]
            res.append(l_forw[i] + 1)
            l_forw[i] = l_forw[l_forw[i]]
            prev = i
        else:
            if prev == i:
                break
            l_next[prev] = l_next[i]
        i = l_next[prev]
    res = [len(res)] + res
    print(' '.join([str(r) for r in res]))
for _ in range(t):
    main()

Solution (Python):
import sys
from collections import deque
from math import gcd
data = sys.stdin.read().split('\n')[::-1]

def input():
    return data.pop()

class Song:

    def __init__(self, v, idx):
        self.v = v
        self.idx = idx

def solve(arr):
    arr = [Song(v, i) for (i, v) in enumerate(arr)]
    ans = []
    gcds = [gcd(arr[i].v, arr[i + 1].v) for i in range(len(arr) - 1)]
    gcds.append(gcd(arr[-1].v, arr[0].v))
    assert len(gcds) == len(arr)
    removed = []
    i = 1
    while i != len(arr) + 1:
        if gcds[(i - 1) % len(arr)] == 1:
            removed.append(arr[i % len(arr)])
            gcds[i % len(arr)] = 0
        i = i + 1
    if not removed:
        return []
    q = deque()
    for i in range(len(arr)):
        if gcds[(i + 1) % len(arr)] == 0 and gcds[i]:
            q.append((i, (i + 1) % len(arr)))
    ans.extend(removed)
    closest = [-1] * len(arr)
    assert len(gcds) == len(arr)
    while q:
        (killer, victim) = q.popleft()
        if gcds[killer] == 0:
            continue
        while gcds[victim] == 0:
            victim = (victim + 1) % len(arr)
        if gcd(arr[killer].v, arr[victim].v) == 1:
            gcds[victim] = 0
            ans.append(arr[victim])
            q.append((killer, victim))
    return [v.idx + 1 for v in ans]
output = []
for _ in range(int(input())):
    n = int(input())
    arr = list(map(int, input().split()))
    solution = solve(arr)
    solution = [len(solution)] + solution
    output.append(' '.join(map(str, solution)))
print('\n'.join(output))