FJUT 奇怪的数列(线性选择算法)题解

题意:找出无需数列中位数(偶数为两个中位数平均数向下取整)

思路:用nth_element(a + first,a + k,a+ end + 1)找出中位数,复杂度一般为O(n)。这个STL能将 [ a + first,a+ end + 1)数组中第k小的数字放在a + k这个位置上,并且k前都比他小,后面都比他大。向下取整应该用 >>1,不要用”/2”  “/2”是向零取整。

代码:

#include<set>
#include<map>
#include<stack>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = 1e6 + 10;
const int seed = 131;
const ll MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
using namespace std;
ll a[maxn];
int main(){
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%lld", &a[i]);
    ll ans;
    if(n & 1){
        nth_element(a + 1, a + n / 2 + 1, a + n + 1);
        ans = a[n / 2 + 1];
    }
    else{
        nth_element(a + 1, a + n / 2, a + n + 1);
        ans = a[n / 2];
        nth_element(a + 1, a + n / 2 + 1, a + n + 1);
        ans += a[n / 2 + 1];
        ans >>= 1;
    }
    printf("%lld\n", ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/KirinSB/p/9788799.html