Codeforces Round #826 (Div. 3) 1741D - Masha and a Beautiful Tree Solution
Problem Link: https://codeforces.com/problemset/problem/1741/D
Solution in C++:
- /// La ilaha illellahu muhammadur rasulullah
- ///******Bismillahir-Rahmanir-Rahim******///
- /// Abul Hasnat Tonmoy
- /// Department of CSE,23rd batch
- /// Islamic University,Bangladesh
- ///**********ALLAH IS ALMIGHTY************///
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> a;
- int ans = 0;
- void func(int l1, int r1, int l2, int r2) {
- int mxl = 0;
- int mnr = INT_MAX;
- for (int i = l1; i <= r1; i++) {
- mxl = max(mxl, a[i]);
- }
- for (int i = l2; i <= r2; i++) {
- mnr = min(mnr, a[i]);
- }
- if (mxl > mnr) {
- int R = l2;
- for (int i = l1; i <= r1; i++) {
- swap(a[i], a[R]);
- R++;
- }
- ans++;
- }
- if (l1 == r1) return;
- int mid1 = (l1 + r1) / 2;
- int mid2 = (l2 + r2) / 2;
- func(l1, mid1, mid1 + 1, r1);
- func(l2, mid2, mid2 + 1, r2);
- }
- int main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- int t;
- cin >> t;
- while (t--) {
- int n;
- cin >> n;
- a.resize(n + 1);
- for (int i = 1; i <= n; i++) cin >> a[i];
- if (is_sorted(a.begin() + 1, a.begin() + n + 1)) {
- cout << 0 << endl;
- continue;
- }
- ans = 0;
- int mid = (n + 1) / 2;
- func(1, mid, mid + 1, n);
- if (is_sorted(a.begin() + 1, a.begin() + n + 1)) {
- cout << ans << endl;
- } else
- cout << "-1" << endl;
- }
- }
No comments