题目地址: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; }