首页 > 代码库 > Codeforces_776B: Sherlock and his girlfriend(素数筛)

Codeforces_776B: Sherlock and his girlfriend(素数筛)

题目链接

题意:对2~n+1染色,一个数不能与其素因子同色。

故而只需两种颜色即可,素数染1,合数染2便可满足条件

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

//素数筛打表 
const int N=1e5+10;
int prime[N+5],num_prime=0;
int isNotPrime[N+5];
void init()
{
    isNotPrime[0]=isNotPrime[1]=1;
    for(int i=2; i<=N; i++)
    {
        if(!isNotPrime[i]) prime[num_prime++]=i;
        for(int j=0; j<num_prime&&i*prime[j]<=N; j++)
        {
            isNotPrime[i*prime[j]]=1;
            if(!(i%prime[j])) break;
        }
    }
}

int main()
{
    int n;
    init();
    while(cin>>n)
    {
        if(n==1||n==2) puts("1");
        else puts("2");
        for(int i=2;i<=n+1;i++)
            printf("%d%c",isNotPrime[i]+1,i==n+1? \n: );
    }
}

 

Codeforces_776B: Sherlock and his girlfriend(素数筛)