C. Ehab and a Special Coloring Problem(数论,构造)

题目链接和题面

题目链接
C. Ehab and a Special Coloring Problem
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You’re given an integer ?. For every integer ? from 2 to ?, assign a positive integer ?? such that the following conditions hold:

For any pair of integers (?,?), if ? and ? are coprime, ??≠??.
The maximal value of all ?? should be minimized (that is, as small as possible).
A pair of integers is called coprime if their greatest common divisor is 1.

Input
The only line contains the integer ? (2≤?≤105).

Output
Print ?−1 integers, ?2, ?3, …, ?? (1≤??≤?).

If there are multiple solutions, print any of them.

Examples
inputCopy
4
outputCopy
1 2 1
inputCopy
3
outputCopy
2 1
Note
In the first example, notice that 3 and 4 are coprime, so ?3≠?4. Also, notice that ?=[1,2,3] satisfies the first condition, but it’s not a correct answer because its maximal value is 3.

题意:

给一个正整数n,要求构造一个数组a[],数组的下标i从2到n。对于任意i, j (i != j),如果i和j互质的话,那么要求a[i]和a[j]不同。

思路:

我们把小于n的素数的个数叫p,我们要构造出的数组的最大值叫max。那么max >= p,因为每个素数跟其他素数都是互质的,所以每个素数都需要分配不同的元素。

所以,我们先给每个小于n的素数分配不同的值(从1到p),然后对于每个合数i,让a[i] = a[i 的最小素因子]即可。

代码

// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define ms(s) memset(s, 0, sizeof(s))
const int inf = 0x3f3f3f3f;
#define LOCAL
const int maxn = 1e6 + 7;
/*
假设最大值为max, 
让小于或者等于n的素数的个数叫p。
然后max >= p是对的,因为必须为每一个素数分配一个不同的数字,因为每个素数都跟其他素数是互质的。
*/

int main(int argc, char * argv[]) 
{
	int n;
	cin >> n;
	int cnt = 0;
	int a[maxn];
	memset(a, 0, sizeof(a));
	for (int i = 2; i * i <= n; i++){
		for (int j = 2; j * i<= n; j++){
			a[i * j] = -1;
		}
	}
	for (int i = 2; i <= n; i++){
		if (a[i] == 0){
			a[i] = ++cnt;
		}
	}
	for (int i = 2; i <= n; i++){
		if (a[i] == -1){
			int t = i;
			for (int j = 2; j * j <= i; j++){
				if (i % j == 0){
					a[i] = a[j];
					break;
				}
			}
		}
	}
	for (int i = 2; i <= n; i++){
		cout << a[i];
		cout << (i == n ? "\n" : " ");
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值