P9325

· · 题解

两篇题解都想麻烦了,因为我们要求不对称性,那么枚举中间的对称点然后向左右两边扩展即可,时间复杂度 O(n^2) ,但因为是向左右扩展,根本跑不满,所以跑的飞快。

具体就是枚举对称点 i ,左右端点 l,r 依次扩展,求出当前不对称性 s ,设 ans_i 为长度为 i 的截图的最小不对称性,那么 ans_{r-l+1} = \min(ans_{r-l+1},s) 。一次求长度为奇数的,一次求长度为偶数的,然后就完了。具体实现非常简单,请看代码。

代码

#include <cmath>
#include <cstring>
#include <iostream>

using namespace std;

int h[5010],ans[5010],l,r,s;

int main()
{
    ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);
    int n;cin >> n;
    memset(ans,0x3f,sizeof(ans));
    for (int i = 1;i <= n;i++) cin >> h[i];
    for (int i = 1;i <= n;i++)
    {
        s = 0,l = r = i;
        while(l && r <= n)
        {
            ans[r-l+1] = min(ans[r-l+1],s);
            l--,r++,s += abs(h[r]-h[l]);
        }

        s = abs(h[i+1]-h[i]),l = i,r = i+1;
        while(l && r <= n)
        {
            ans[r-l+1] = min(ans[r-l+1],s);
            l--,r++,s += abs(h[r]-h[l]);    
        }
    }
    for (int i = 1;i <= n;i++) cout << ans[i] << ' ';
    return 0;
}