poj2388
快排或者随机快排都超时。
快排:
#include <stdio.h> #include <stdlib.h> int n; int d[10005]; int partition(int a[], int p, int r) { double x = a[r]; int i = p - 1; int temp; for(int j=p; j<r; j++) if(a[j] <= x) { i++; temp = a[j]; a[j] = a[i]; a[i] = temp; } temp = a[i+1]; a[i+1] = a[r]; a[r] = temp; return i + 1; } void quickSort(int a[], int p, int r) { if(p < r) { int q = partition(a, p, r); quickSort(a, p, q-1); quickSort(a, p+1, r); } } int main() { while(~scanf("%d", &n)) { for(int i=0; i<n; i++) scanf("%d", &d[i]); quickSort(d, 0, n-1); printf("%d\n", d[(n-1)/2]); } return 0; }
随机快排:
#include <stdio.h> #include <stdlib.h> int n; int d[10005]; int partition(int a[], int p, int r) { double x = a[r]; int i = p - 1; int temp; for(int j=p; j<r; j++) if(a[j] <= x) { i++; temp = a[j]; a[j] = a[i]; a[i] = temp; } temp = a[i+1]; a[i+1] = a[r]; a[r] = temp; return i + 1; } int randomizedPartition(int a[], int p, int r) { int i = rand() % (r-p) + p; int temp = a[r]; a[r] = a[i]; a[i] = temp; return partition(a, p, r); } void quickSort(int a[], int p, int r) { if(p < r) { int q = randomizedPartition(a, p, r); quickSort(a, p, q-1); quickSort(a, p+1, r); } } int main() { while(~scanf("%d", &n)) { for(int i=0; i<n; i++) scanf("%d", &d[i]); quickSort(d, 0, n-1); printf("%d\n", d[(n-1)/2]); } return 0; }
sort函数:
#include <iostream> #include <algorithm> using namespace std; int n; int d[10005]; int main() { while(cin >> n) { for(int i=0; i<n; i++) cin >> d[i]; sort(d, d+n); cout << d[(n-1)/2]; } return 0; }