前言
最近听一个学长讲了如何利用比特串求解排名第k
位的数据,觉得还挺巧妙的
分析
下面以求解排名第k
位和成绩第k
小(即倒数排名为k
)的学生成绩为例解释算法思路:
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #include <iostream> #include <vector> #include <assert.h> using namespace std; #define N 101
int main() { int n; cout << "请输入学生人数: "; cin >> n; vector<int> grade(n); vector<int> bit(N, 0); vector<vector<int>> bit_grade(n, bit);
for (int i = 0; i < n; ++i) { cout << "请输入第" << i + 1 << "位学生的成绩: "; cin >> grade[i]; assert(grade[i] >= 0 && grade[i] <= 100); bit_grade[i][grade[i]] = 1; }
for (int i = 0; i < N; ++i) { for (int j = 0; j < n; ++j) { bit[i] += bit_grade[j][i];
if (bit[i] > 1) bit[i] = 1; } }
int k, sum = 0; int choice, stop = 1;
while (stop == 1) { sum = 0; cout << "正向排名请填1, 反向排名请填2: "; cin >> choice;
if (choice == 1) { cout << "请问您需要排名第几的数据: "; cin >> k; for (int i = 100; i >= 0; --i) { if (sum >= k) { cout << "排名第" << k << "的数据是: " << i + 1 << endl; break; } else { sum += bit[i]; } }
cout << "继续请填1, 停止请填2: "; cin >> stop; cout << endl; } else { assert(choice == 2); cout << "请问您需要第几小的数据: "; cin >> k; for (int i = 0; i < 101; ++i) { if (sum >= k) { cout << "第" << k << "小的数据是: " << i - 1 << endl; break; } else { sum += bit[i]; } }
cout << "继续请填1, 停止请填2: "; cin >> stop; cout << endl; } }
return 0; }
|