1537C - Challenging Cliffs - CodeForces Solution


constructive algorithms greedy implementation math *1200

Please click on ads to support us..

Python Code:

import sys
inp = sys.stdin.readline
input = lambda: inp().strip()
ii = lambda: int(input())
mi = lambda: map(int,input().split())
li = lambda: list(map(int,input().split()))
ms = lambda: map(input().split())
ls = lambda: list(input().split())
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop,heapify

for _ in range(ii()):
    n = ii()
    nums = li()
    nums.sort()
    mins = (-1,-1,float('inf'))
    for i in range(1,len(nums)):
        if nums[i] - nums[i-1] < mins[2]:
            mins = (i-1,i,nums[i]-nums[i-1])
    print(nums[mins[0]],end=' ')
    for i in range(mins[1]+1,len(nums)):
        print(nums[i],end=' ')
    for j in range(mins[0]):
        print(nums[j], end=' ')
    print(nums[mins[1]])

C++ Code:

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ul;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<int>> vvi;
typedef map<int, int> mi;
typedef map<ll, ll> ml;
typedef set<int> si;
typedef set<ll> sl;
typedef pair<int, int> pi;
typedef unordered_set<int> uis;
typedef unordered_set<ll> uls;
typedef pair<ll, ll> pl;


#define PA(a, n) for(int i = 0; i < n; i++) cout << a[i] << ' '
#define PV(v) for(auto i : v) cout << i << ' '
#define YES cout << "YES\n"
#define NO cout << "NO\n"


int main(){
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  int t;
  cin >> t;
  while(t--){
    ll n;
    cin >> n;

    ll h[n];
    for(ll i = 0; i <n; i++) cin >> h[i];

    sort(h, h + n);

    ll ans[n];

    ll md = LLONG_MAX;
    ll ind = 0;

    for(ll i = 0; i <= n-2; i++){
      if(abs(h[i] - h[i+1]) < md){
        md = abs(h[i]-h[i+1]);
        ind = i;
      }
    }

    ans[0] = h[ind];
    ans[n-1] = h[ind+1];

    ll ci = (ind + 2) % n;
    for(ll i = 1; i <= n-2; i++){
      ans[i] = h[ci];
      ci = (ci+1) % n;
    }

    PA(ans, n);
    cout << '\n';

  }

  return 0;
}


Comments

Submit
0 Comments
More Questions

1684A - Digit Minimization
43B - Letter
1017A - The Rank
1698B - Rising Sand
235A - LCM Challenge
1075B - Taxi drivers and Lyft
1562A - The Miracle and the Sleeper
1216A - Prefixes
1490C - Sum of Cubes
868A - Bark to Unlock
873B - Balanced Substring
1401D - Maximum Distributed Tree
1716C - Robot in a Hallway
1688B - Patchouli's Magical Talisman
99A - Help Far Away Kingdom
622B - The Time
1688C - Manipulating History
1169D - Good Triple
1675B - Make It Increasing
588A - Duff and Meat
1541B - Pleasant Pairs
1626B - Minor Reduction
1680A - Minimums and Maximums
1713A - Traveling Salesman Problem
1713B - Optimal Reduction
1710A - Color the Picture
1686B - Odd Subarrays
251A - Points on Line
427C - Checkposts
1159A - A pile of stones