1772D - Absolute Sorting - CodeForces Solution


constructive algorithms math *1400

Please click on ads to support us..

Python Code:

from math import ceil
def sorting_value(nums, x = 0):

    if sorted(nums) == nums: return x
    if sorted(nums, reverse= True) == nums: return nums[0] + 1

    x = []
    for i in range(1,len(nums)):
        if nums[i - 1] > nums[i]:
            x += [ceil ((nums[i - 1] + nums[i]) / 2)]

    
    x = max(x)
    sorted_nums = [abs (num - x) for num in nums]

    if sorted(sorted_nums) == sorted_nums: return x

    return -1

if __name__ == "__main__":
    for _ in range(int(input())):
        input()
        nums = [int(x) for x in input().split()]

        value = sorting_value(nums)
        print (value)

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;

int main()
{
    int t;
    cin >> t;
    for(int i = 0; i < t; i++)
    {
        int n;
        cin >> n;
        vector<int> a(n);
        for(int j = 0; j < n; j++)
            cin >> a[j];
        int mn = 0, mx = int(1e9);
        for(int j = 0; j + 1 < n; j++)
        {
            int x = a[j];
            int y = a[j + 1];
            int midL = (x + y) / 2;
            int midR = (x + y + 1) / 2;
            if(x < y)
                mx = min(mx, midL);
            if(x > y)
                mn = max(mn, midR);
        }
        if(mn <= mx) cout << mn << endl;
        else cout << -1 << endl;
    }
}


Comments

Submit
0 Comments
More Questions

320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales
734B - Anton and Digits
1080A - Petya and Origami
1642D - Repetitions Decoding
1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing
1348A - Phoenix and Balance
1343B - Balanced Array
1186A - Vus the Cossack and a Contest
1494A - ABC String
1606A - AB Balance
1658C - Shinju and the Lost Permutation
1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition
1609C - Complex Market Analysis
1657E - Star MST