题解:#小红构造数组#

小红构造数组

https://ac.nowcoder.com/acm/contest/73422/E

首先就是筛出他的因子,从i=2开始枚举,筛出的因子一定为素数,比如4是因子那么在i=2时就应该会把2给筛完

     for(int i = 2; i * i <= x; i ++) {
        if(x % i == 0) {
            int cnt = 0;
            while(x % i == 0) {
                cnt ++; x /= i;
            }
            a.push_back({cnt, i});
            sum += cnt;
        }
    }

如果x % i == 0,这个i不为素数,那就说明i还能分解,那么在i更小的时候就应该全部筛掉了,不可能不是素数,将结果放入vectora当中,按出现次数来排序,只需要将次数多的放好了,那么出现次数少的一定没有问题,所以按出现次数从大到小排序然后把元素放入到队列中,间隔一个放入,再判断相邻元素是否相等。 另外就是1需要特判,分解之后只有一个元素1,不是素数,应该输出-1

  #include<bits/stdc++.h>
using namespace std;

#define x first
#define y second 
#define Yes cout << "Yes\n"
#define No cout << "No\n"
#define YES cout << "YES\n"
#define NO cout << "NO\n"
#define ls u << 1
#define rs u << 1 | 1
#define all(x) x.begin(),x.end()
#define int long long
#define i128 __int128

inline int gcd(int a, int b) {return b > 0 ? gcd(b, a % b) : a;}
inline int lowbit(int x) {return x & (-x);}
int qmi(int a, int b, int mod){int res = 1;while(b) {if(b & 1) res = res * a % mod;a = a * a % mod;b >>= 1;}return res;}
inline i128 read(){i128 x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}
inline void print(i128 x){if(x < 0){putchar('-');x = -x;}if(x > 9)print(x / 10);putchar(x % 10 + '0');}

void solve()
{
    int x; cin >> x;
    vector<PII>a;
    int sum = 0;
    if(x == 1) {
        cout << -1 << '\n';
        return;
    }
    for(int i = 2; i * i <= x; i ++) {
        if(x % i == 0) {
            int cnt = 0;
            while(x % i == 0) {
                cnt ++; x /= i;
            }
            a.push_back({cnt, i});
            sum += cnt;
        }
    }
    if(x > 1) a.push_back({1, x}), sum += 1;
    sort(all(a), greater<PII>());
    vector<int>v(sum);
    int j = 0;
    for(int i = 0; i < sum; i += 2) {
        v[i] = a[j].y;
        a[j].x --;
        if(a[j].x == 0) j ++;
    }
    for(int i = 1; i < sum; i += 2) {
        v[i] = a[j].y;
        a[j].x --;
        if(a[j].x == 0) j ++;
    }
    for(int i = 0; i < sum - 1; i ++)
        if(v[i] == v[i + 1]) {
            cout << -1 << '\n';
            return;
        }
    cout << sum << '\n';
    for(int i = 0; i < sum; i ++) cout << v[i] << ' ';
}

signed main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int t = 1;
    // cin >> t;
    while (t--)
    {
        solve();
    }
} 
全部评论
tql
点赞 回复 分享
发布于 2024-01-21 22:14 江西
最开始就是这么写的,一直不过,后来直接换dfs无脑写
点赞 回复 分享
发布于 2024-01-21 22:15 江西
太好懂了这个代码
点赞 回复 分享
发布于 2024-01-22 12:07 江西
%%%
点赞 回复 分享
发布于 2024-01-28 12:45 河北
呜呜呜喵
点赞 回复 分享
发布于 2024-04-05 21:34 北京

相关推荐

2024-12-21 18:48
西安邮电大学 C++
黑皮白袜臭脚体育生:按使用了什么技术解决了什么问题,优化了什么性能指标来写会更好另外宣传下自己的开源仿b站微服务项目,GitHub已经390star,牛客上有完整文档教程
点赞 评论 收藏
分享
给🐭🐭个面试机会吧:我boss直聘天天有家教跟我打招呼😓
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务