码迷,mamicode.com
首页 > 其他好文 > 详细

数列极差

时间:2019-09-21 11:04:44      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:cpp   include   char   cst   tmp   ace   algorithm   getch   using   

题目描述

思路

代码

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int n, arr[50005], save[50005];
int tmp[50005];
long long  maxx, minn;
const int inf = 0x7fffffff;
inline int read() {
    int s = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s * f;
}
int cmpa(int a, int b) {
    return a < b;
}
int cmpb(int a, int b) {
    return a > b;
}
void inserta(int * arr, int tot, int key) {
    for (int i = tot; i >= 0; --i) {
        if (arr[i] > key) arr[i + 1] = arr[i]; 
        else {
            arr[i + 1] = key;
            break;
        }
    }
}
void insertb(int * arr, int tot, int key) {
    for (int i = tot; i >= 0; --i) {
        if (arr[i] < key) arr[i + 1] = arr[i]; 
        else {
            arr[i + 1] = key;
            break;
        }
    }
}
void show(int * r, int n) {
    for (int i = 1; i <= n; ++i) {
        printf("%d ", r[i]);
    }
    puts("");
}
int main() {
    n = read();
    for (int i = 1; i <= n + 1; ++i) arr[i] = read();
    memcpy(save, arr, sizeof(arr));
    sort(arr + 1, arr + 1 + n, cmpa);
    for (int i = n; i >= 3; --i) {
        for (int j = 1; j <= i - 2; ++j) tmp[j] = arr[j + 2];
        inserta(tmp, i - 2, arr[1] * arr[2] + 1);
        for (int j = 1; j <= i - 1; ++j) arr[j] = tmp[j];  
    }
    maxx = arr[1] * arr[2] + 1;
    memcpy(arr, save, sizeof(arr));
    sort(arr + 1, arr + n + 1, cmpb);
    for (int i = n; i >= 3; --i) {
        for (int j = 1; j <= i - 2; ++j) tmp[j] = arr[j + 2];
        tmp[0] = inf;
        insertb(tmp, i - 2, arr[1] * arr[2] + 1);
        for (int j = 1; j <= i - 1; ++j) arr[j] = tmp[j];
    }
    minn = arr[1] * arr[2] + 1;
    printf("%lld\n", maxx - minn);
    return 0;
}

数列极差

标签:cpp   include   char   cst   tmp   ace   algorithm   getch   using   

原文地址:https://www.cnblogs.com/liuzz-20180701/p/11561565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!