题解:CF2246D diss_quack and Array Game
CF2246D 題解
這題也是神了,我感覺是同等級別最難的題目
題意
Alice 和 Bob 一起玩一個游戲,有一個長度為
每一輪:
Bob 先手,可以交換數組中2個數,也可以不交換。
Alice 後手,如果
如果一個數字變為0,它將會被移除。
當數組為空的時候,游戲結束。
Alice 需要令總操作數最少,Bob 需要令 Alice 的操作數最多。求 Alice最少的操作數。
思路
我們透過貪心發現,如果數組的開頭是一大段連續的偶數,Alice 可以很賺,一下子把很多數除以二。Bob 的策略自然就是,如果數組裏面有奇數,就立刻把這個奇數通過交換換到
推導
我們定義
如果
如果
然後我們發現原來
Alice 的策略
前面提到將數字轉化成偶數可以大大減少操作次數,我們在初始的時候通過操作將數組的數增加,使得每一個數都可以表達成
固定
這裡有一個貪心誤區:有些稍微大一點的
代碼
#include <bits/stdc++.h>
#define int long long
#define pii pair<int,int>
#define fi first
#define se second
#define endl '\n'
#define pb push_back
using namespace std;
const int N = 200050;
const int INF = 1e18;
int f[N+50];
int b[20][N+50];
int a[N+50];
void pre(){
f[1] = 1;
for (int i = 2; i < N+20; i++){
if (i&1) f[i] = f[i/2]+2;
else f[i] = f[i/2]+1;
}
for (int i = 0; i <= 18; i++){
int lim = N>>i;
for (int j = 1; j <= lim + 5; j++){
b[i][j] = (j<<i)+f[j];
}
for (int j = lim+4; j >= 1; j--){
b[i][j] = min(b[i][j],b[i][j+1]);
}
}
}
void solve(){
int n; cin >> n;
int ans = INF;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 0; i <= 18; i++){
int cur = i;
for (int j = 1; j <= n; j++){
int need = (a[j]+(1LL<<i)-1)>>i;
cur += b[i][need]-a[j];
}
ans = min(ans,cur);
}
cout << ans << endl;
}
signed main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
pre();
int _t; cin >> _t;
while (_t--) solve();
return 0;
}
時間複雜度為