类似原题:https://codeforces.com/problemset/problem/1553/D
每个质因子给做好下标的索引然后并查集连通。
比较trick的是最后sort后来check一下当前的数字的下标和正确位置的下标是不是在一个连通块里。
这个check的部分和cf的一道div2B是类似的。
const int maxn=2e5+1000;
typedef int LL;
typedef pair<int,int>P;
class Solution {
public:
LL fa[maxn],a[maxn],p[maxn];
P e[maxn];
LL find(LL x)
{
if(fa[x]==x) return fa[x];
else return fa[x]=find(fa[x]);
}
void un(LL x,LL y)
{
LL u=find(x); LL v=find(y);
if(u==v) return;
fa[u]=v;
}
bool gcdSort(vector<int>& nums) {
int n=nums.size();
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=n;i++) a[i]=nums[i-1];
for(int i=1;i<=n;i++)
{
int temp=a[i];
for(int j=2;j<=sqrt(temp);j++)
{
if(temp%j==0)
{
if(p[j]) un(p[j],i);
else p[j]=i;
while(temp>1&&temp%j==0) temp/=j;
}
}
if(temp>1)
{
if(p[temp]) un(p[temp],i);
else p[temp]=i;
}
e[i]={a[i],i};
}
bool flag=1;
sort(e+1,e+1+n);
for(int i=1;i<=n;i++)
{
if(find(i)!=find(e[i].second)) return 0;
}
return 1;
}
};