CF959D 构造

1 CF959D 构造

2 题目描述

时间限制 \(3s\) | 空间限制 \(256M\)

Mahmoud has an array a consisting of \(n\) integers. He asked Ehab to find another array \(b\) of the same length such that:

  • \(b\) is lexicographically greater than or equal to a.
  • \(b_i ≥ 2\).
  • \(b\) is pairwise coprime: for every \(1 ≤ i < j ≤ n\), \(b_i\) and \(b_j\) are coprime, i. e. \(GCD(b_i, b_j) = 1\), where \(GCD(w, z)\) is the greatest common divisor of \(w\) and \(z\).

Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?

An array \(x\) is lexicographically greater than an array \(y\) if there exists an index \(i\) such than \(x_i > y_i\) and \(x_j = y_j\) for all \(1 ≤ j < i\). An array \(x\) is equal to an array \(y\) if \(x_i = y_i\) for all \(1 ≤ i ≤ n\).

数据范围:\(1 ≤ n ≤ 10^5\)

3 题解

容易想到,我们构造的每一个数都必须不含有之前所构造出的所有数的每个质因数,否则不满足互质这一条件。也就是说,我们可以在每一个数确定之后,找出这个数所有的质因数,并且在 \(2 \times 10^6\) 的值域内筛去所有的质因数的倍数。如果我们发现,有一时刻我们必须选择大于 \(a_i\) 的某个数来保证当前序列满足要求,那么我们之后选择的数就不再受 \(b_i \ge a_i\) 这一限制条件了。那么我们如何找到在筛选后大于等于 \(a_i\) 的第一个满足要求的数在哪里呢?

我们可以考虑使用 \(multiset\) 记录可以选择的数。一开始将 \(2\)\(2\times 10^6\) 这些数插入 \(multiset\) 中,每次筛选后将不符合的数消除。当我们还没有出现 \(b_i > a_i\) 的情况时,我们每次用 \(lowerbound\) 函数找到第一个大于等于 \(a_i\) 的数。否则,我们每次找到符合要求的数中最小的数即可。

4 代码(空格警告):

#include <iostream>
#include <set>
#include <cmath>
using namespace std;
const int N = 1e5+10;
const int M = 2e6+10;
int n, cnt;
int a[N], c[N], b[N];
multiset<int> s;
void filter(int x)
{
    int cnt = 0;
    for (int i = 2; i <= sqrt(x); i++)
    {
        if (x % i == 0)
        {
            while (x % i == 0) x /= i;
            c[++cnt] = i;
        }
    }
    if (x > 1) c[++cnt] = x;
    for (int i = 1; i <= cnt; i++)
    {
        for (int j = 1; j <= M / c[i]; j++) s.erase(c[i] * j);
    }
}
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    for (int i = 2; i <= M; i++) s.insert(i);
    for (int i = 1; i <= n; i++)
    {
        cnt = i+1;
        multiset<int>::iterator it = s.lower_bound(a[i]);
        b[i] = *it;
        filter(b[i]);
        if (b[i] > a[i]) break;
    }
    for (int i = cnt; i <= n; i++)
    {
        multiset<int>::iterator it = s.begin();
        b[i] = *it;
        filter(b[i]);
    }
    for (int i = 1; i <= n; i++) cout << b[i] << " ";
    return 0;
}

欢迎关注我的公众号:智子笔记

posted @ 2021-04-12 21:43  David24  阅读(77)  评论(0编辑  收藏  举报