题解:P14566 【MX-S12-T1】取模

· · 题解

设 a_1,a_2,\cdots,a_n 的最大值为 mx,严格次大值为 sc,最小值为 mn。

综上所述,答案就是 \max(mx-mn,sc)。

注意把 sc 求成非严格次大值会导致挂 30。

代码:

#include<bits/stdc++.h>
using namespace std;
int qread(){
    int x;
    char c;
    while(1){
        c = getchar();
        if(c >= '0' && c <= '9')break; 
    }
    x = c - '0';
    while(1){
        c = getchar();
        if(c >= '0' && c <= '9')x = (x << 3) + (x << 1) + c - '0';
        else break;
    }
    return x;
}
int main(){
    int t, n, x, mx, sc, mn;
    cin >> t;
    while(t--){
        cin >> n;
        mx = sc = -1;
        mn = 1000000001;
        for(int i = 1; i <= n; i++){
            x = qread();
            if(x > mx){
                sc = mx;
                mx = x;
            }else if(x > sc && x != mx)sc = x;
            if(x < mn)mn = x;
        }
        cout << max(mx - mn, sc) << "\n";
    }
    return 0;
}