ACdream群赛14---A题瑶瑶的第K大

题目地址:http://acdream.info/onecontest/1026#problem-A

这个题真坑啊。。。卡时间卡得真严。。。即使用个O(n)的算法都超时。。还得进行输入优化。。不过通过这个题知道了怎样输入优化,对于那些输入量特大的题可以挽救不少时间。。其实就是利用字符输入快的优势转换成整型。

输入优化函数代码为;

int read(){
	int x = 0;
	char ch = ' ';
	while(ch < '0' || ch > '9') ch = getchar();
	while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
	return x;
}
此题用上了O(n)的算法,(比快排都快好多倍。。)还用上了输入优化。。才以4300ms险过。。(题目时间限制是5000ms)代码如下:

#include <stdio.h>
#include <string.h>
int a[10000000];
template<typename T>
int partition(T array[], int low, int high)
{
    T x = array[low];
    while(low < high)
    {
        while(low < high && array[high] <= x) --high;
        array[low] = array[high];
        while(low < high && array[low] >= x) ++low;
        array[high] = array[low];
    }
    array[low] = x;
    return low;
}

/*返回a中第k大的元素,复杂度为O(n)*/
void search(int *a, int i, int j, int k)
{
    if(i <= j)
    {
        int q = partition(a, i, j);
        /*if a[q] is the key looking for, then print it*/
        if(q-i+1 == k)
        {
            /*be careful about the index*/
            printf("%d\n",a[q]);
            return;
        }
        else if(q-i+1 < k)
        {
            /*look for the k-(q-i+1) th max number in [q+1, j]*/
            search(a, q+1, j, k-(q-i+1));
        }
        else
        {
            /*look for the k th max number in [i, q-1]*/
            search(a, i, q-1, k);
        }
    }
}
int read(){
	int x = 0;
	char ch = ' ';
	while(ch < '0' || ch > '9') ch = getchar();
	while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
	return x;
}
int main()
{
    int n, k, i;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        for(i=0;i<n;i++)
            a[i]=read();
        search(a,0,n-1,k);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值