线段树基础 poj2104

来源:互联网 发布:阿里云下载 编辑:程序博客网 时间:2024/05/16 10:09

题目链接

题目描述

有N个数,1~N,存在数列a[1~N]中(无序),输入i,j,k。求a[i ~ j] 之间第K小数。如 数列:1 5 2 6 3 7 4. 输入2 5 4 .输出:6

思路

  1. 用一个结构体存储输入元素的值和当前所在位置
  2. 将结构体按照输入元素值排序
  3. 从1 ~ N遍历每个元素,统计位置在i,j之间的元素个数,统计到第K个,这个位置对应的元素的值就是所求答案
    如下图

代码

#include <iostream>#include <cstdio>#include <algorithm>using namespace std;struct Node{  int pos,val;}nodes[110000];bool cmp(const Node n1, const Node n2){    return n1.val < n2.val;}int main(){    int N,M;    scanf("%d%d",&N,&M);    for(int i = 1; i<=N; i++){        scanf("%d",&nodes[i].val);        nodes[i].pos = i;    }    sort(nodes+1, nodes+N+1, cmp);    while(M--){        int a,b;        scanf("%d%d",&a,&b);        int cnt;        scanf("%d",&cnt);        int i;        int res = 0;        for(i = 1; i<=N; i++){            if(a<=nodes[i].pos && nodes[i].pos<=b){                res++;                if(res == cnt) break;            }        }        printf("%d\n",nodes[i].val);    }    return 0;}
0 0
原创粉丝点击