P1923 【深基9.例4】求第 k 小的数(快速选择算法)

发布时间 2023-08-18 17:33:49作者: 上原歩夢

 

题解:

  利用快速排序的思想来寻找第k小的数,可以避免很多不必要的操作

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 5000005, M = 5e6 + 5;
 4 int x[N], k;
 5 inline int read(int &s)
 6 {
 7     s = 0;
 8     int w = 1;
 9     char ch = getchar();
10     while (ch < '0' || ch > '9')
11     {
12         if (ch == '-')
13             w = -1;
14         ch = getchar();
15     }
16     while (ch >= '0' && ch <= '9')
17     {
18         s = s * 10 + ch - '0';
19         ch = getchar();
20     }
21     return s * w;
22 }
23 void qsort(int l, int r)
24 {
25     int i = l, j = r, mid = x[(l + r) / 2];
26     do
27     {
28         while (x[j] > mid)
29             j--;
30         while (x[i] < mid)
31             i++;
32         if (i <= j)
33         {
34             swap(x[i], x[j]);
35             i++;
36             j--;
37         }
38     } while (i <= j);
39     // 快排后数组被划分为三块: l<=j<=i<=r
40     if (k <= j)
41         qsort(l, j); // 在左区间只需要搜左区间
42     else if (i <= k)
43         qsort(i, r); // 在右区间只需要搜右区间
44     else             // 如果在中间区间直接输出
45     {
46         printf("%d", x[j + 1]);
47         exit(0);
48     }
49 }
50 int main()
51 {
52     int n;
53     scanf("%d %d", &n, &k);
54     for (int i = 0; i < n; i++)
55         read(x[i]);
56     qsort(0, n - 1);
57 }

 

STL大法:

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 const int N = 5e6 + 5;
 5 int a[N];
 6 inline int read(int &s)
 7 {
 8     s = 0;
 9     int w = 1;
10     char ch = getchar();
11     while (ch < '0' || ch > '9')
12     {
13         if (ch == '-')
14             w = -1;
15         ch = getchar();
16     }
17     while (ch >= '0' && ch <= '9')
18     {
19         s = s * 10 + ch - '0';
20         ch = getchar();
21     }
22     return s * w;
23 }
24 inline void write(int x)
25 {
26     if (x < 0)
27     {
28         putchar('-');
29         x = -x;
30     }
31     if (x > 9)
32         write(x / 10);
33     putchar(x % 10 + '0');
34 }
35 int main()
36 {
37     int n, k;
38     scanf("%d %d", &n, &k);
39     for (int i = 0; i < n; ++i)
40         read(a[i]);
41     nth_element(a, a + k, a + n);
42     write(a[k]);
43 }