Codeforces Round #400 B.Sherlock and his girlfriend

题目

Sherlock has a new girlfriend (so unlike him!). Valentine’s day is coming and he wants to gift her some jewelry.

He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, … n + 1.

Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don’t have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.

Help Sherlock complete this trivial task.

Input
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

Output
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints.

The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price.

If there are multiple ways to color the pieces using k colors, you can output any of them.

Examples
input
3
output
2
1 1 2

input
4
output
2
2 1 1 2

代码

#include
 #include
 #include
 using namespace std;
 int main()
 {
    int n = 0;
    cin >> n;
    int a[n+1];
    memset(a,0,sizeof(a));
    for(int i = 2;i <= n+1;i++)
    {
        if(!a[i])
        for(int j = 2;i*j <= n+1;j++)
        {
            a[i*j] = 1;
        }
    }
    if(n > 2)
    {
        cout << "2" << endl;
        for(int i = 2;i <= n+1;i++)
        {
            if(!a[i])
            cout << "2";
            else
            cout << "1";
            if(i != n+1)
            cout << " ";
        }
    }
    else
    {
        cout << "1" << endl;
        for(int i = 2;i <= n+1;i++)
        {
            cout << "1";
            if(i != n+1)
            cout << " ";
        }
    }
    return 0;
 }

理解

这个题说的是,给你几个宝石,编号从2开始往后到n+1,然后,如果一块是另一块的素因数,那么涂成不同的颜色,最多两种颜色,现在给你块数,然后问最少几种颜色,怎么涂。
这实际上就是在找质数,用埃氏筛法,把质数找出来,然后跟合数涂不同色就可以了,但要注意,n是从2开始,所以要注意一下3以下的情况。

你可能感兴趣的:(Codeforces Round #400 B.Sherlock and his girlfriend)