Part 1 二分查找
-
lower_bound
:查找有序序列中第一个大于等于给定值的数的数组下标; -
upper_bound
:查找有序序列中第一个大于给定值的数的数组下标。 -
binary_search
:查找序列中是否有给定的值下面给出它们的两种写法,分别使用 STL 容器 vector \text{vector} vector 和数组:
#include<bits/stdc++.h> using namespace std; vector<int> a = {1, 5000, 2, 3, 4, 100, 50, 60, 80, 73}; int main() { sort(a.begin(), a.end()); //对原数组进行排序 cout << lower_bound(a.begin(), a.end(), 50) - a.begin() << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的下标 cout << a[lower_bound(a.begin(), a.end(), 50) - a.begin()] << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的值 cout << *lower_bound(a.begin(), a.end(), 50) << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的值,只不过此处用了指针的写法 cout << upper_bound(a.begin(), a.end(), 50) - a.begin() << "\n"; //二分查找序列 a 中第一个大于 50 的数的下标 cout << a[upper_bound(a.begin(), a.end(), 50) - a.begin()] << "\n"; //二分查找序列 a 中第一个大于 50 的数的值 cout << *upper_bound(a.begin(), a.end(), 50) << "\n"; //和上面一样,二分查找序列 a 中第一个大于 50 的数的值,只不过此处用了指针的写法 cout << binary_search(a.begin(), a.end(), 4) << "\n"; //查找序列中有没有 4 cout << binary_search(a.begin(), a.end(), 10); //查找序列中有没有 10 return 0; }
#include<bits/stdc++.h> using namespace std; int a[10] = {1, 5000, 2, 3, 4, 100, 50, 60, 80, 73}; int main() { sort(a, a + 10); //对原数组进行排序 cout << lower_bound(a, a + 10, 50) - a << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的下标 cout << a[lower_bound(a, a + 10, 50) - a] << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的值 cout << *lower_bound(a, a + 10, 50) << "\n"; //二分查找序列 a 中第一个大于等于 50 的数的值,只不过此处用了指针的写法 cout << upper_bound(a, a + 10, 50) - a << "\n"; //二分查找序列 a 中第一个大于 50 的数的下标 cout << a[upper_bound(a, a + 10, 50) - a] << "\n"; //二分查找序列 a 中第一个大于 50 的数的值 cout << *upper_bound(a, a + 10, 50); //和上面一样,二分查找序列 a 中第一个大于 50 的数的值,只不过此处用了指针的写法 cout << binary_search(a, a + 10, 4) << "\n"; //查找序列中有没有 4 cout << binary_search(a, a + 10, 10); //查找序列中有没有 10 return 0; }
对于上述三种函数的参考,详见 lower_bound \text{lower\_bound} lower_bound、 upper_bound \text{upper\_bound} upper_bound 和 binary_search \text{binary\_search} binary_search。
Part 2 全排列
-
next_permutation
:重新排序范围中的元素,使用按字典顺序的下一个更大排列(如果存在)替换原有排序。和上一部分一样,给出两种写法,分别使用 STL 容器 vector \text{vector} vector 和数组:
#include<bits/stdc++.h> using namespace std; vector<int> a = {1, 2, 3}; int main() { do { for (auto i : a) cout << i << " "; cout << "\n"; } while (next_permutation(a.begin(), a.end())); return 0; }
#include<bits/stdc++.h> using namespace std; int a[3] = {1, 2, 3}; int main() { do { for (int i = 0; i < 3; i++) cout << i << " "; cout << "\n"; } while (next_permutation(a, a + 3); return 0; }
对于本函数的参考详见 next_permutation \text{next\_permutation} next_permutation。