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 ai , 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 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 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] → [5, 9, 2,
10, 15] → [5, 2, 10, 15] (because gcd(5,9)=1) → [5, 2, 10, 15] → [5,
2, 10, 15] → [5, 2, 10, 15] → [5, 2, 10, 15] → [5, 2, 10, 15] → [5,
10, 15] (because gcd(5,2)=1) → [5, 10, 15] → [5, 10, 15] →… 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.
有些题目其实你知道怎么写,你就是得去学手法吧,感觉手法真的很重要。
#include <iostream>
#include <vector>
#include<string>
using namespace std;
const int N = 1e5 + 5;
int a[N], ne[N];
bool st[N];
int gcd (int a, int b)
{
return b ? gcd (b, a % b) : a;
}
int main()
{
int t;
cin >> t;
while (t --)
{
int n;
cin >> n;
vector <int> del;
for (int i = 0; i < n; i ++)
{
cin >> a[i];
st[i] = 0;
ne[i] = (i + 1) % n;
del.push_back (i);
}
vector <int> ans;
while (del.size())
{
vector <int> newdel;
for (auto it : del)
{
if (st[it]) continue;
if (gcd (a[it], a[ne[it]]) == 1)
{
ans.push_back (ne[it] + 1);
st[ne[it]] = 1;
ne[it] = ne[ne[it]];
newdel.push_back (it);
}
}
del = newdel;
}
cout << ans.size();
for (int it : ans) cout << " " << it;
cout << endl;
}
return 0;
}