直接快排没意思。。。
于是想写写"快速选择算法"。。。结果啊。。。
调了1h。。。欧我去。。。至于么,已经蒟蒻到这种程度了?
反正我是记住你了快速选择。。。!
1 /************************************************************** 2 Problem: 1753 3 User: rausen 4 Language: C++ 5 Result: Accepted 6 Time:8 ms 7 Memory:844 kb 8 ****************************************************************/ 9 10 #include <cstdio> 11 #include <algorithm> 12 13 using namespace std; 14 const int N = 10005; 15 int n, a[N]; 16 17 inline int read(){ 18 int x = 0; 19 char ch = getchar(); 20 while (ch < '0' || ch > '9') 21 ch = getchar(); 22 while (ch >= '0' && ch <= '9'){ 23 x = x * 10 + ch - '0'; 24 ch = getchar(); 25 } 26 return x; 27 } 28 29 int find(int l, int r, int rank){ 30 int i = l, j = r + 1; 31 int x = a[l]; 32 while (1){ 33 while (a[++i] < x); 34 while (x < a[--j]); 35 if (i > j) break; 36 swap(a[i], a[j]); 37 } 38 swap(a[l], a[j]); 39 if (j - l + 1 == rank) return a[j]; 40 else if (j - l + 1 > rank) return find(l, j - 1, rank); 41 else return find(j + 1, r, rank - (j - l + 1)); 42 } 43 44 int main(){ 45 n = read(); 46 int i; 47 for (i = 1; i <= n; ++i) 48 a[i] = read(); 49 printf("%d\r\n", find(1, n, (n + 1) >> 1)); 50 return 0; 51 }
By Xs酱~ 转载请说明
博客地址:http://www.cnblogs.com/rausen