題目傳送門
題意:
給你 個數 ,每次操作可以使一個數增加 或 減少 。操作後需要保證這個數是正數。
問你最少操作多少次使這些數的 大於 。
數據範圍: 。
題解:
我們讓每個數都變成 的倍數,上界是 。
如果有超過一半的數變化超過 ,那麼就超過上界了。
所以最多有一半的數的變化不能超過 。
我們在序列中隨機一個數 ,然後枚舉 的質因子作爲整個序列的 。
因爲每次隨機失敗的概率是 ,那麼 次隨機失敗的概率大概是 。
感受:
常數寫的有點大。
看題解之前能想到必須得知道gcd是什麼才能做,但接下來推不下去了。
其實這種題也只能是隨機了,但是不看題解確實想不到。
代碼:
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 2e5 + 5 ;
const int maxm = 1e6 + 5 ;
const int inf = 0x3f3f3f3f ;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()) ;
int n , m ;
ll a[maxn] ;
int cnt = 0 ;
bool vis[maxm] ;
int prime[maxm] ;
void get_prime()
{
memset(vis , 0 , sizeof(vis)) ;
vis[1] = 1 ;
for(int i = 2 ; i <= maxm - 5 ; i ++)
{
if(!vis[i])
prime[++ cnt] = i ;
for(int j = 1 ; j <= cnt && i * prime[j] <= maxm - 5 ; j ++)
{
vis[i * prime[j]] = 1 ;
if(i % prime[j] == 0) break ;
}
}
}
ll work(ll x)
{
ll num = 0 ;
for(int i = 1 ; i <= n ; i ++)
{
ll y = a[i] % x ;
if(a[i] < x) num += x - y ;
else num += min(y , x - y) ;
}
return num ;
}
ll cal(ll x)
{
ll ans = 1e18 ;
if(x <= 1) return ans ;
for(int i = 1 ; i <= cnt && prime[i] <= x ; i ++)
{
if(x % prime[i] != 0) continue ;
ans = min(ans , work(ll(prime[i]))) ;
while(x % prime[i] == 0) x /= prime[i] ;
}
if(x > 1) ans = min(ans , work(x)) ;
return ans ;
}
ll solve(ll x)
{
ll ans = 1e18 ;
ans = min(ans , cal(a[x] - 1)) ;
ans = min(ans , cal(a[x])) ;
ans = min(ans , cal(a[x] + 1)) ;
return ans ;
}
int main()
{
ll ans = 0 ;
scanf("%d" , &n) ;
for(int i = 1 ; i <= n ; i ++) scanf("%lld" , &a[i]) ;
get_prime() ;
for(int i = 1 ; i <= n ; i ++)
if(a[i] % 2 == 1) ans ++ ;
for(int i = 1 ; i <= 30 ; i ++)
{
int x = rnd() % n + 1 ;
ans = min(ans , solve(x)) ;
}
printf("%lld\n" , ans) ;
return 0 ;
}