1454F - Array Partition - CodeForces Solution


binary search data structures greedy two pointers *2100

Please click on ads to support us..

C++ Code:

// https://codeforces.com/problemset/problem/1454/F
#include <bits/stdc++.h>
using namespace std;
const int N = 2 * 1e5 + 5;
const int LOG = 18;
int mn[N][LOG], mx[N][LOG];
bool fl;
int getmin(int l, int r)
{
    int len = r - l + 1;
    int k = 0;
    while ((1 << (k + 1)) <= len)
        ++k;
    return min(mn[l][k], mn[r - (1 << k) + 1][k]);
}
int getmax(int l, int r)
{
    int len = r - l + 1;
    int k = 0;
    while ((1 << (k + 1)) <= len)
        ++k;
    return max(mx[l][k], mx[r - (1 << k) + 1][k]);
}
bool valid(int l, int r, int n)
{
    if (l < 1 || l >= r - 1 || r > n)
        return 0;
    int lf = getmax(1, l);
    int md = getmin(l + 1, r - 1);
    int rg = getmax(r, n);
    if (lf == md && lf == rg)
    {
        cout << "YES\n"
             << l << ' ' << r - l - 1 << ' ' << n - r + 1 << '\n';
        fl = 1;
        return 1;
    }
    return 0;
}
int main()
{
    cin.tie(0)->ios_base::sync_with_stdio(0);
    int t;
    cin >> t;
    while (t--)
    {
        fl = 0;
        int n;
        cin >> n;
        vector<int> a(n + 5);
        for (int i = 1; i <= n; ++i)
            cin >> a[i], mn[i][0] = mx[i][0] = a[i];
        for (int j = 1; j < LOG; ++j)
            for (int i = 1; i + (1 << j) - 1 <= n; ++i)
            {
                mn[i][j] = min(mn[i][j - 1], mn[i + (1 << (j - 1))][j - 1]);
                mx[i][j] = max(mx[i][j - 1], mx[i + (1 << (j - 1))][j - 1]);
            }
        int lf = 0;
        int r = n;
        for (int l = 1; l < n - 1; ++l)
        {
            lf = max(lf, a[l]);
            while (r - 1 > l && a[r] <= lf)
                --r;
            ++r;
            while (r - 1 <= l)
                ++r;
            if (valid(l, r, n) || valid(l - 1, r, n) || valid(l, r + 1, n))
                break;
        }
        if (!fl)
            cout << "NO\n";
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

760B - Frodo and pillows
1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books
1374B - Multiply by 2 divide by 6
1093B - Letters Rearranging
1213C - Book Reading
1468C - Berpizza
1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel
1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes