5866. 数组的最大公因数排序(CF1553D)

类似原题: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;
}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值