[CF449C] Jzzhu and Apples

[CF449C] Jzzhu and Apples - 构造

Description

给出正整数n,你要把1-n之间的正整数分成尽可能多组,使得每一组两个数的最大公约数大于1;输出能分成最多组的个数,并按任意顺序输出每组的两个数

Solution

降序枚举质因数,考察还剩多少个它的倍数,偶数个就两两匹配,奇数个就把 (2p) 留下来

#include <bits/stdc++.h>
using namespace std;

#define int long long

int n;
set<int> s;
vector<pair<int, int>> ans;

signed main()
{
    ios::sync_with_stdio(false);

    cin >> n;
    for (int i = 1; i <= n; i++)
        s.insert(i);

    for (int i = n / 2; i >= 2; i--)
    {
        int flag = 1;
        for (int j = 2; j * j <= i; j++)
            if (i % j == 0)
            {
                flag = 0;
                break;
            }
        if (flag == 0)
            continue;
        set<int> t;
        for (int j = i; j <= n; j += i)
            if (s.find(j) != s.end())
            {
                s.erase(j);
                t.insert(j);
            }
        if (t.size() & 1)
        {
            if (t.find(2 * i) != t.end())
            {
                t.erase(2 * i);
                s.insert(2 * i);
            }
        }
        while (t.size() >= 2)
        {
            int a = *t.begin(), b = *t.rbegin();
            ans.push_back({a, b});
            t.erase(a);
            t.erase(b);
        }
    }
    cout << ans.size() << endl;
    for (auto [x, y] : ans)
        cout << x << " " << y << endl;
}
原文地址:https://www.cnblogs.com/mollnn/p/14659003.html