题意:
给出一个长度为 n n n的数组,数组成一个环,每次从下标为 1 1 1 的地方开始遍历,到 n n n 后又重新回到 1 1 1,假设当前遍历到 i i i ,如果 g c d ( a [ i − 1 ] , a [ i ] ) = 1 gcd(a[i-1],a[i])=1 gcd(a[i−1],a[i])=1 那么就将 a [ i ] a[i] a[i] 删除,删除后,如果 g c d ( a [ i + 1 ] , a [ i − 1 ] ) = 1 gcd(a[i+1], a[i-1])=1 gcd(a[i+1],a[i−1])=1 ,那么不能直接将 a [ i + 1 ] a[i+1] a[i+1]删除,要等到下一次遍历再判断。问一共删掉多少数,并且按顺序输出下标。
题解:
先用数组模拟链表,维护出每个当前数组每个位置的前一个位置和下一个位置。 p r e [ i ] pre[i] pre[i] 代表 i i i 前一个位置, n e x [ i ] nex[i] nex[i] 代表 i i i 后一个位置。
再用队列去存储可能被删除的位置,那么具体怎么操作呢?
一开始,我们先遍历数组,将所有相邻位 g c d = 1 gcd=1 gcd=1 的位置的给放入队列中,即如果 g c d ( a [ i ] , a [ i − 1 ] ) = 1 gcd(a[i],a[i-1])=1 gcd(a[i],a[i−1])=1 ,那么就把 i i i 放入队列中,表示这个位置有可能被删除,并且标记此位置在队列中。
然后就是不断删除队首,假设 i i i 位置被删除,那么 p r e [ i ] pre[i] pre[i] 和 n e x [ i ] nex[i] nex[i] 就会相邻,如果这两个数的 g c d = 1 gcd=1 gcd=1 ,那么 n e x [ i ] nex[i] nex[i] 就要被放到队列里,但是光这样还不行,因为前面指出,队列里面放的只是有可能被删除的位置,那么在删除 i i i 的时候,就要判断 n e x [ i ] nex[i] nex[i] 是否在队列里,如果在,就要从队列中移走,因为 n e x [ i ] nex[i] nex[i] 受 i i i的影响被放到队列中,所以在 i i i 被删除的时候,那么 n e x [ i ] nex[i] nex[i] 自然要从队列中移走。
最后再更新一下链表即可。
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<ctime>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int>pii;
const int MAXN=1e5+5;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
int nex[MAXN],pre[MAXN];
queue<int>q;
int a[MAXN];
int vis[MAXN];
std::vector<int> ans;
int gcd(int x,int y)
{
return y?gcd(y,x%y):x;
}
int main()
{
int t;
cin>>t;
while(t--)
{
ans.clear();
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
nex[i]=i+1;
pre[i]=i-1;
vis[i]=0;
}
nex[n]=1;
pre[1]=n;
for(int i=2;i<=n;i++)
{
if(gcd(a[i],a[i-1])==1)
{
vis[i]=1;
q.push(i);
}
}
if(gcd(a[n],a[1])==1)
{
vis[1]=1;
q.push(1);
}
while(!q.empty())
{
int now=q.front();
q.pop();
ans.push_back(now);
if(ans.size()==n) break;
vis[now]=0;
if(vis[nex[now]])//假如后面的元素被标记,说明是在上面的for被放入队列中,那么队列的下一个值一定是nex[i]
{
q.pop();
vis[nex[now]]=0;
}
if(gcd(a[pre[now]],a[nex[now]])==1)
{
vis[nex[now]]=1;
q.push(nex[now]);
}
nex[pre[now]]=nex[now];
pre[nex[now]]=pre[now];
}
printf("%d ",ans.size());
for(int i=0;i<ans.size();i++)
{
printf("%d ",ans[i]);
}
printf("\n");
while(!q.empty())
{
q.pop();
}
}
}