codeforces1305F 隨機

題目傳送門

題意:

給你 n 個數 a_i ,每次操作可以使一個數增加 1 或 減少 1 。操作後需要保證這個數是正數。

問你最少操作多少次使這些數的 gcd 大於 1 。

數據範圍: 1 \leqslant n \leqslant 2 \cdot 10^5 \;,\; 1 \leqslant a_i \leqslant 10^9 。

題解:

我們讓每個數都變成 \dpi{150} 2 的倍數,上界是 n 。

如果有超過一半的數變化超過 1 ,那麼就超過上界了。

所以最多有一半的數的變化不能超過 1 。

我們在序列中隨機一個數 a_i ,然後枚舉 a_i - 1 \;,\;a_i\;,\;a_i+1 的質因子作爲整個序列的 gcd 。

因爲每次隨機失敗的概率是 \frac{1}{2} ,那麼 30 次隨機失敗的概率大概是 10^{-9} 。 

感受:

常數寫的有點大。

看題解之前能想到必須得知道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 ;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章