CF 1872 D

发布时间 2023-09-08 12:51:24作者: 铜锣骚

D. Plus Minus Permutation

这道题要使\((p_{1 \cdot x} + p_{2 \cdot x} + \ldots + p_{\lfloor \frac{n}{x} \rfloor \cdot x}) - (p_{1 \cdot y} + p_{2 \cdot y} + \ldots + p_{\lfloor \frac{n}{y} \rfloor \cdot y})\)最大,只需要让位置为\(x\)倍数的位置尽可能大,让位置为\(y\)倍数的位置尽可能小。其中位置为\(lcm(x, y)\)倍数的位置会同时加减一次,所以只要计算出位置为\(x\)倍数且不是\(lcm(x, y)\)倍数的个数以及位置为\(y\)倍数且不是\(lcm(x, y)\)倍数的个数,则\(numx=n/x-n / (x * y / gcd(x, y))\),\(numy=n/y-n / (x * y / gcd(x, y))\),最终答案即

\[Ans=(n + n - numx + 1) * numx / 2 - (1 + numy) * numy / 2 \]

代码

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;

const ll N = 1e7 + 10;
ll t;
ll n, x, y;

signed main()
{
    std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while(t--)
    {
        cin >> n >> x >> y;
        ll numx = n / x, numy = n / y, numg = n / (x * y / gcd(x, y));
        numx -= numg;
        numy -= numg;
        ll tot = (n + n - numx + 1) * numx / 2 - (1 + numy) * numy / 2;
        cout << tot << endl;
    }
    return 0;
}