Sherlock and his girlfriend (Codeforces-776B)

来源:互联网 发布:富通天下软件下载 编辑:程序博客网 时间:2024/05/18 16:13

题目链接:

http://codeforces.com/problemset/problem/776/B

B. Sherlock and his girlfriend
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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
21 1 2 
input
4
output
22 1 1 2

题目大意:

一个人要用尽量少的颜色 给 n块珠宝涂色(编号为1-n),其中第 i 块珠宝的价格为 i+1 。规定:如果一块珠宝的价格 是 另一块珠宝价格 的质因子,那么这两块珠宝不能涂同样的颜色。其中颜色用数字表示(即同样的数字表示同样的暗色)。题目要求输出:第一行输出最少使用的颜色数量,第二行输出1-n块珠宝的颜色(颜色用数字表示,从1开始)。如果有多种情况,那么输出任意一种。

解题思路:

根据 算数基本定理任何一个大于1的自然数N,如果N不为质数,那么N可以唯一分解为有限个质数的乘积

     有了这个定理,是不是感觉这道题太水了?我们来分析一下:由算数基本定理得:每一个大于1的非质数都有质因子。所以这道题就转化为:把 价格 为质数的珠宝涂成1颜色,把 价格 不是质数的珠宝涂成2颜色。所以只需要两种颜色即可。但是有特殊情况,下面请看特殊情况:

          (1)如果n==1,那么需要一种颜色,颜色为1;

          (2)如果n==2,那么需要两种颜色,颜色为1 2;

          (3)如果n==3,根据上面那个定理和我写的解题思路做即可。

     注意:判断是否为素数一定要按耗时较少的判断方法,按照普通的判断方法会时间超限。耗时较少的素数判断方法:http://blog.csdn.net/jiyi_xiaoli/article/details/77185007

代码:

#include<iostream>using namespace std;int isprime(int x)   //判断是否为素数的函数{    int i;    if(x==1)        return 0;    for(i=2;i*i<=x;i++)    {        if(x%i==0)            return 0;    }    return 1;}int main(){    int s,n;    while(cin>>n)    {        if(n==1)   //特殊情况1            cout<<1<<endl<<1<<endl;        else if(n==2)   //特殊情况2        {            cout<<1<<endl<<1<<' '<<1<<endl;            continue;        }        else        {            cout<<2<<endl;   //最多只需要两种颜色            for(int i=2;i<=n+1;i++)            {                if(isprime(i)==1)   //如果是素数,把颜色涂为1                    cout<<1<<' ';                else   //不是素数,把颜色涂为2                    cout<<2<<' ';            }            cout<<endl;        }    }    return 0;}


阅读全文
1 0