2020NYIST个人积分赛第八场 D _求中位数——模拟+二分查找优化 HDU - 3282

12 篇文章 0 订阅

更:正解是堆,应该是题目水了


题目大意: 给你n个数,每当输入奇数个数时,就输出前面这些数的中位数。


模拟即可,可以用stl库函数upper_bound() 快速求出第一个比当前输入值大的值,将该值已经往后位置的值全部后移一个位置,然后即可得到中位数。


AC代码:
//https://blog.csdn.net/hesorchen
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI cos(-1)
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000009
#define lowbit(abcd) (abcd & (-abcd))

ll ans[1000010], ans_ct = 1;
ll p[1000010];
int main()
{
    ll t;
    cin >> t;
    while (t--)
    {
        ans_ct = 1;
        fill(p, p + 100001, 0);
        ll pos = 1;
        ll num, n;
        cin >> num >> n;
        for (int i = 1; i <= n; i++)
        {
            ll a;
            scanf("%lld", &a);
            ll temp = upper_bound(p, p + 1 + pos, a) - p; //二分快速定位
            // for (int i = 1; i <= pos; i++)
            //     cout << p[i] << ' ';
            // cout << endl;
            // cout << a << ' ' << temp << endl;
            for (int i = pos; i >= temp; i--) //将比当前值大的值往右移动
                p[i + 1] = p[i];
            // cout << "#" << temp << ' ' << pos + 1 << endl;
            if (temp == pos + 1) //如果二分没找到比当前值大的值,直接放最后面
                temp = pos;
            if (temp == 0) //如果所有与值都比当前值大,直接放最前面。
                temp = 1;
            p[temp] = a;
            if (i % 2) //如果前面已经输入奇数个数  存当前中位数答案
            {
                if (pos % 2 == 1) //找到中位数
                    // printf("%lld ", p[(pos + 1) / 2]);
                    ans[ans_ct++] = p[(pos + 1) / 2];
                else
                // printf("%lld ", (p[pos / 2] + p[pos / 2 + 1]) / 2);
                {
                    ll ttemp = (p[pos / 2] + p[pos / 2 + 1]) / 2;
                    if ((p[pos / 2] + p[pos / 2 + 1]) % 2)
                        ttemp++;
                    ans[ans_ct++] = temp;
                }
            }
            pos++;
        }
        printf("%lld %lld\n", num, ans_ct - 1);
        ll sss = 0;
        for (int i = 1; i < ans_ct - 1; i++)
        {
            sss++;
            if (sss % 10 == 0) //十个换行
                printf("%lld\n", ans[i]);
            else
                printf("%lld ", ans[i]);
        }
        printf("%lld\n", ans[ans_ct - 1]);
    }

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hesorchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值