Codeforces Round #563 (Div. 2) C. Ehab and a Special Coloring Problem(素数筛)

题目链接:https://codeforces.com/contest/1174/problem/C

题意

构造一个下标从 $2$ 到 $n$,大小为 $n - 1$ 的数组,要求如果两个元素下标互质,它们的值不能相同,且所用数应尽可能地小。

题解

类似素数筛,依次把不互质的下标构造为同一值即可。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n; cin >> n;
    int a[n + 1] = {};
    int num = 1;
    for (int i = 2; i <= n; i++) {
        if (a[i]) continue;
        for (int j = i; j <= n; j += i)
            if (a[j] == 0)
                a[j] = num;
        ++num;
    }
    for (int i = 2; i <= n; i++)
        cout << a[i] << ' ';
}

 

posted @ 2020-06-13 20:07  Kanoon  阅读(121)  评论(0)    收藏  举报