B
merge和binary_search的用法
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;int main()
{int n, m;cin >> n >> m;vector<int> a(n), b(m), c(n + m);for (int i = 0; i < n; i++){cin >> a[i];}for (int j = 0; j < m; j++){cin >> b[j];}sort(a.begin(), a.end());sort(b.begin(), b.end());merge(a.begin(), a.end(), b.begin(), b.end(), c.begin());for(int i = 0; i < n + m - 1; i++){if (binary_search(a.begin(), a.end(), c[i]) && binary_search(a.begin(), a.end(), c[i + 1])){cout << "Yes";return 0;}}cout << "No";return 0;
}
merge
当你需要合并两个已经排序好的序列时,merge 函数是一个很有用的工具。它可以将两个有序序列合并成一个新的有序序列。merge 函数接受四个迭代器参数:两个输入序列的起始和结束迭代器,以及输出序列的起始迭代器。以下是 merge 函数的基本用法示例
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;int main() {vector<int> a = {1, 3, 5};vector<int> b = {2, 4, 6};vector<int> c(a.size() + b.size());merge(a.begin(), a.end(), b.begin(), b.end(), c.begin());cout << "Merged sequence: ";for (int num : c) {cout << num << " ";}cout << endl;return 0;
}
binary_search 函数
它用于在有序序列中查找特定元素。如果找到了该元素,则返回 true;否则返回 false。binary_search 函数接受两个迭代器参数:序列的起始和结束迭代器,以及要查找的值。以下是 binary_search 函数的基本用法示例:
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;int main() {vector<int> v = {1, 3, 5, 7, 9};int target = 5;if (binary_search(v.begin(), v.end(), target)) {cout << "Found " << target << " in the sequence." << endl;} else {cout << target << " not found in the sequence." << endl;}return 0;
}