第X大的数
Problem Description
X最近爱上了区间查询问题,给出N (N <= 100000) 个数,然后进行M (M <= 50) 次询问,每次询问时,输入一个数X (1 <= X <= N),输出N个数中第X大的数。
Input
多组输入。
每组首先输入一个整数N,代表有N个数,下面一行包含N个整数,用空格隔开。然后为一个整数M,代表有M次询问,下面的M行,每行一个整数X。
Output
输出N个数中第X大的数。
Sample Input
4
1 2 2 3
4
1
2
3
4
Sample Output
3
2
2
1
Hint
快排一趟 加 搜索
#include <stdio.h>
#include "stdlib.h"
int qs (int a[], int l, int r)
{
int i = l, j = r;
int key = a[l];
while(i < j)
{
while(i < j && key >= a[j])
j--;
a[i] = a[j];
while(i < j && key <= a[i])
i++;
a[j] = a[i];
}
a[i] = key;
return i;
}
int find(int a[], int l, int r,int x)
{
int i;
if(l <= r)
{
i = qs(a, l, r);
if(i == x)
{
return a[i];
}
if(i > x)
{
return find(a, l, i - 1, x);
}
else
{
return find(a, i + 1, r, x);
}
}
else return -1;
}
int main()
{
int a[1000005];
int n, i, m, ask;
while(~scanf("%d",&n))
{
for(i = 1; i <= n; i++)
scanf("%d",&a[i]);
scanf("%d",&m);
while(m--)
{
scanf("%d",&ask);
printf("%d\n",find(a, 1 ,n, ask));
}
}
return 0;
}