Gym - 101466 J. Jeronimo's List 桶排序

转自:https://blog.csdn.net/prolightsfxjh/article/details/79321161

题目链接:http://codeforces.com/gym/101466/problem/J

题意:

一共n个数字(3<=n<=3e7, 0<=ai<3e7 ),给出前面的m个(3<=m<=min(100, n)),
a[i] = (a[i-m] + a[i-m+1]) % MOD,q个询问(1<=q<=1e4),询问a[1,n]里的从小到大第bi大。

桶排序

先按照要求用a[1,m]构造出a[1,n],然后这里n == 3e7,所以如果采用快速的比较排序算法如归并排序快速排序的时间复杂度是O(nlogn)会超时,因此我们想到可以使用线性排序方法桶排序(或者说计数排序),建一个数组cnt[3e7+8],扫一遍a数组,对于每一个ai,cnt[a[i]]++,最后扫一遍cnt数组,就可以把ai排好序了。

for(i = 0; i < MOD; i++){
while(cnt[i]){
a[ptr] = i;
ptr++;
cnt[i]–; }
}

时间复杂度 O(n)

空间复杂度 O(n)

代码:

#include <iostream>
#include <cstdio>

using namespace std;
typedef long long LL;
const int MAXN = 3e7 + 8;
const int MOD = 3e7;
int cnt[MAXN], a[MAXN];

int main()
{
    #ifdef LOCAL
    freopen("j.txt", "r", stdin);
    //freopen("j.out", "w", stdout);
    int T = 4;
    while(T--){
    #endif // LOCAL
    //ios::sync_with_stdio(false); cin.tie(0);

    int n, m, q, i, x;
    //cin >> n >> m >> q;
    scanf("%d%d%d", &n, &m, &q);
    for(i = 1; i <= m; i++) scanf("%d", &a[i]); //cin >> a[i];
    for(i = m+1; i <= n; i++){
        a[i] = (a[i-m] + a[i-m+1])%MOD;
    }
    for(i = 1; i <= n; i++){
        cnt[a[i]]++;
    }
    int ptr = 0;
    for(i = 0; i < MOD; i++){
        while(cnt[i]){
            a[ptr] = i;
            ptr++;
            cnt[i]--;
        }
    }
    for(i = 0; i < q; i++){
        //cin >> x;
        scanf("%d", &x);
        //cout << a[x-1] << "\n";
        printf("%d\n", a[x-1]);
    }



    #ifdef LOCAL
    cout << endl;
    }
    #endif // LOCAL
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值