B. Motarack's Birthday

题目意思:

给你一串数组,其中-1代表未知,求相邻两个数之差的绝对值最小

想法:

我们先假设 -1 的位置代表 k ,那么我们要让它和它前后两个数的最大差值最小 也就是 | k-a |  | k-b | | k-c | .... 那么会发现其实也就是和 a,b,c .. 中最大的、最小的差值要最小

那么就是 k 的值应该就是 max和 min的中间值 

找到了 k 再去跑一遍整个数组,求得整个是数组的最大差值

#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <math.h>
#include <cstdio>
#include <iomanip>
#include <time.h>
#include <bitset>
#include <cmath>

#define LL long long
#define INF 0x3f3f3f3f
#define ls nod<<1
#define rs (nod<<1)+1

const double eps = 1e-10;
const int maxn = 1e5 + 10;
const LL mod = 1e9 + 7;

int sgn(double a){return a < -eps ? -1 : a < eps ? 0 : 1;}
using namespace std;

int a[maxn];
int n;

int main() {
    int T;
    cin >> T;
    while (T--) {
        cin >> n;
        int l = INF,r = 0;
        for (int i = 1;i <= n;i++) {
            cin >> a[i];
        }
        for (int i = 1;i <= n;i++) {
            if (a[i] == -1) {
                if (i-1 >= 1 && a[i-1] != -1)
                    l = min(l,a[i-1]),r = max(r,a[i-1]);
                if (i+1 <= n && a[i+1] != -1)
                    l = min(l,a[i+1]),r = max(r,a[i+1]);
            }
        }
        int mid = (l + r) >> 1;
        int m = 0;
        for (int i = 1;i+1 <= n;i++) {
            int k1 = a[i],k2 = a[i+1];
            if (k1 == -1)
                k1 = mid;
            if (k2 == -1)
                k2 = mid;
            m = max(m,abs(k1-k2));
        }
        cout << m << " " << mid << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/-Ackerman/p/12325736.html