题解归档 - cf2227E

题解归档 - cf2227E

本文由 cf-code 本地题解库自动归档;公开内容以本地 AC/验证版本为准。

思路

cf2227E - It All Went Sideways

pattern: row compaction counted by suffix minima.

claim: for a fixed height h, cubes that do not move are exactly the trailing occupied suffix in that row. Summing over all heights, the number of unmoved cubes is sum_i min(a_i..a_n). Thus the initial moved count is sum(a) - sum(suffix_min).

single decrease: decreasing a_p by 1 lowers exactly those suffix minima suffix_min[i] with i <= p and suffix_min[i] == a_p. If this count is d, total cubes drops by 1 and fixed cubes drops by d, so the moved count improves by d - 1.

algorithm: scan left to right, maintain frequencies of suffix_min[i] among processed positions, and maximize freq[a[p]].

check: brute row simulation on random small arrays.

代码

来源:problems/cf2227E/solution.cpp

/* Author: likely
 * Time: 2026-06-27
**/
#include<bits/stdc++.h>
#define ll long long
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<int>a(n+2),suf(n+3);
        ll total=0,fixed=0;
        for(int i=1;i<=n;i++){
            cin>>a[i];
            total+=a[i];
        }
        suf[n+1]=n+1;
        for(int i=n;i>=1;i--){
            suf[i]=min(a[i],suf[i+1]);
            fixed+=suf[i];
        }
        vector<int> freq(n+2,0);
        int best=0;
        for(int i=1;i<=n;i++){
            freq[suf[i]]++;
            best=max(best,freq[a[i]]);
        }
        ll ans=total-fixed+max(0,best-1);
        cout<<ans<<"\n";
    }
    return 0;
}
~  ~  The   End  ~  ~


 赏 
感谢您的支持,我会继续努力哒!
支付宝收款码
tips
文章二维码 分类标签:归档TypechoAutoUpload
文章标题:题解归档 - cf2227E
文章链接:https://www.fangshaonian.cn/archives/250/
最后编辑:2026 年 6 月 28 日 19:05 By 方少年
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
(*) 4 + 6 =
快来做第一个评论的人吧~