Loading

CF1305F Kuroni and the Punishment 题解

一道比较简单的题,我居然调了这么久。

思路

看一眼这个题,发现好像没有什么思路。

考虑来用一些巧妙的手法,比如随机化。

首先证明一个结论,至少有一半的数只会被操作一次或者不操作。

这个结论比较好证明。

可以知道,答案一定小于等于 \(\text{n}\)

所以如果有超过一半的数会被操作两次。

那么这个答案必然不是最优的答案。

所以,我们可以随即选出一个数 \(\text{x}\),将 \(\text{x}\)\(x+1\)\(x-1\) 分解质因数,来判断这个质数是否可以更新答案,每次找到最优的概率是 \(\frac{1}{2}\)

这样,就可以随机找出 \(\text{50}\) 个数来判断即可。

错误的概率为 \(\frac{1}{2^{50}}\)

一个细节

这个细节让我调了特别久。

当你在用 \(\text{rand}\) 调用随机数时,请不要这样写。

x = rand() % n + 1;

请这样写。

x = rand() * rand() % n + 1;

一个惨痛的教训。

Code

#include <bits/stdc++.h>
#define int long long
using namespace std;
 
const int N = 200010;
 
int n , ans , top , a[N] , stk[N];
 
inline int read()
{
    int asd = 0 , qwe = 1; char zxc;
    while(!isdigit(zxc = getchar())) if(zxc == '-') qwe = -1;
    while(isdigit(zxc)) asd = asd * 10 + zxc - '0' , zxc = getchar();
    return asd * qwe;
}
 
inline void calc(int x)
{
    for(int i = 2;i * i <= x;i++)
    {
        if(x % i == 0)
            stk[++top] = i;
        while(x % i == 0)
            x /= i;
    }
    if(x != 1) stk[++top] = x;
}
 
inline void solve(int x)
{
    int sum = 0;
    for(int i = 1;i <= n;i++)
        sum += min((a[i] >= x ? a[i] % x : (int)1e17) , x - a[i] % x);
    ans = min(ans , sum);
}
 
signed main()
{
    n = read() , srand(time(0));
    for(int i = 1;i <= n;i++)
        a[i] = read() , ans += (a[i] & 1);
    int res = 50;
    while(res--)
    {
        int x = rand() * rand() % n + 1;
        calc(a[x]) , calc(a[x] + 1) , calc(a[x] - 1);
    }
    sort(stk + 1 , stk + top + 1);
    top = unique(stk , stk + top + 1) - stk - 1;
    for(int i = 1;i <= top;i++) solve(stk[i]);
    cout << ans << endl;
    return 0;
}

posted @ 2022-09-07 13:11  JiaY19  阅读(35)  评论(0编辑  收藏  举报