B - Piano 2 Editorial by en_translator
This problem asks to rearrange elements in a sequence in specific order. This operation is called sort, which is provided as a standard feature in most languages. For example, Python and C++ both provides a function named sort
.
To solve the problem, concatenate \(A\) and \(B\) to define \(C\), sort \(C\), inspect the elements of \(C\), and check if adjacent elements are both contained in \(A\).
To determine if a value is contained in a sequence, it is useful to use the in
operator in Python, and set
operator in C++, for example.
Sample code (Python)
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = A + B
C.sort()
for i in range(N + M - 1):
if C[i] in A and C[i + 1] in A:
print("Yes")
exit()
print("No")
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N, M;
cin >> N >> M;
vector<int> A(N), B(M);
for (auto& x : A) cin >> x;
for (auto& x : B) cin >> x;
auto C = A;
for (auto x : B) C.push_back(x);
sort(C.begin(), C.end());
set<int> st(A.begin(), A.end());
for (int i = 0; i < N + M - 1; ++i) {
if (st.contains(C[i]) && st.contains(C[i + 1])) {
cout << "Yes" << endl;
return 0;
}
}
cout << "No" << endl;
}
posted:
last update: