题解:P14028 【MX-X20-T2】「FAOI-R7」最小极差(jicha)

· · 题解

P14028 【MX-X20-T2】「FAOI-R7」最小极差 - 题解

解题思路 / Solution:

记 p_i 为 a_i 被操作的次数,则 a_i 最终的取值范围为:[a_i - p_i, a_i + p_i]。p_i 可用差分求出。

不难想到,一个数组的极差由以下两个关键值决定:

最终数组的极差为 \max(R - L, 0)。

复杂度分析 / Complexity:

差分 p_i 和求 L, R 的时间复杂度均为线性, 总时间复杂度为 O(T(n+m))。

代码 / Code:

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 2e5+10;

int T;

int n, m;
int a[MAXN];
int p[MAXN];
int L, R;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cin>>T;
    while(T--)
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++) cin>>a[i];
        memset(p, 0 ,sizeof(p));
        L = INT_MAX, R = INT_MIN;
        while(m--)
        {
            int l, r;
            cin>>l>>r;
            p[l]++, p[r+1]--;
        }
        for(int i=1;i<=n;i++) p[i] += p[i-1];
        for(int i=1;i<=n;i++)
        {
            L = min(L, a[i] + p[i]);
            R = max(R, a[i] - p[i]);
        }
        cout<<max(R - L, 0)<<'\n';
    }
    return 0;
}

完结撒花!~
觉得写得不错的话就请点个赞吧 qwq。