洛谷题单指南-进阶数论-CF776B Sherlock and his girlfriend

原题链接:https://www.luogu.com.cn/problem/CF776B

题意解读:将2~n+1的数字进行分类,不能和素因子分在一类,分类越少越好

解题思路:

所有素数显然可以分为一类,其余合数为另外一类,只用标记素数即可,埃氏筛解决。

主要当数字为2或者2、3时,没有合数,只用分成一类,特判处理即可。

100分代码:

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

const int N = 100005;
bool vis[N];
int n;

int main()
{
    cin >> n;
    if(n < 3) 
    {
        cout << 1 << endl;
        for(int i = 1; i <= n; i++) cout << 1 << " ";
        return 0;
    }
    for(int i = 2; i <= n + 1; i++)
    {
        if(!vis[i])
        {
            for(int j = i + i; j <= n + 1; j += i) vis[j] = true;
        }
    }
    cout << 2 << endl;
    for(int i = 2; i <= n + 1; i++) cout << (vis[i] ? 2 : 1) << " ";
    return 0;
}

 

posted @ 2025-10-15 18:38  hackerchef  阅读(6)  评论(0)    收藏  举报