a160簡單陣列、排序與區間掃描

TOI 2022/12 新手組:不穩定的礦石

找到唯一最高能量礦石,先取左右各 A/2 顆,再把不足側的數量補到另一側。

前往題目練習 →回報教學錯誤時間 O(N) ・ 空間 O(N)

這題在學什麼

找到唯一最高能量礦石,先取左右各 A/2 顆,再把不足側的數量補到另一側。

以包含中心的半開區間 [left,right) 表示被合併的礦石。先截到地圖範圍;需要的總長度為 min(N,A+1),若不足先向左擴,再向右補足。

區間和是吸收後中心能量;原總和減去區間和是其餘礦石剩餘能量。當 A≥N-1 時區間就是全陣列。

Step-by-step animation

吸收區間與邊界補足

回報動畫錯誤
步驟 1 / 3

找到中心

第3顆能量30最大,A=4,每側先取2顆。

3
8
30
5
9
2
中心箱號
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main(){int n,a; cin>>n>>a; vector<int>t(n); for(int &x:t) cin>>x;
    int p=max_element(t.begin(),t.end())-t.begin(),left=max(0,p-a/2),right=min(n,p+a/2+1);
    int need=min(n,a+1)-(right-left),take=min(left,need); left-=take; need-=take; right+=need;
    int gain=accumulate(t.begin()+left,t.begin()+right,0),total=accumulate(t.begin(),t.end(),0);
    cout<<gain<<' '<<total-gain<<'\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多