解题报告:HDU_6040 Hints of sd0061 STL::nth_element

本文介绍了一种利用C++ STL中的nth_element函数高效查找序列中第k小元素的方法,并通过一个具体实例展示了如何在多次询问下,快速找到给定序列递推函数生成的序列上的第k小数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接


题意:

给你一个序列的递推函数,m次询问,询问这个序列上第bi小的数。


官方题解:


最关键的部分在于了解STL里的nth_element函数,简单介绍一下:


这个函数的时间复杂度近似线性

函数的调用(取第n小):nth_element ( arr.begin() ,   arr+n,arr.end() )

调用函数后保证比第n个数小的数都在前面,比它大的数在后面




代码:

#include<bits/stdc++.h>

using namespace std;

int id[105],A[105];
unsigned s[10000005];
unsigned ans[105];
int n,m;
unsigned x,y,z;

unsigned oper(){
   unsigned t ;
   x ^= x << 16;
   x ^= x >> 5;
   x ^= x << 1;
   t = x;
   x = y;
   y = z;
   z = t ^ x ^ y;
   return z;
}

bool cmp(int a,int b){
   return A[a] < A[b];
}

int main()
{
   int cas = 0;
   while(scanf("%d%d%u%u%u",&n,&m,&x,&y,&z)==5){
      for(int i=0;i<m;i++){
         id[i] = i;
         scanf("%d",&A[i]);
      }A[m]=n;id[m]=m;
      for(int i=0;i<n;i++)s[i] = oper();
      sort(id,id+m,cmp);
      for(int now,i=m-1,last=A[id[m]];i>=0;i--,last=now){
         now = A[id[i]];
         if(now==last){
            ans[id[i]] = ans[id[i+1]];
         }else {
            nth_element(s,s+now,s+last);
            ans[id[i]] = s[now];
         }
      }printf("Case #%d:",++cas);
      for(int i=0;i<m;i++){
         printf(" %u",ans[i]);
      }printf("\n");
   }return 0;
}

















评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值