676A - Nicholas and Permutation

  1. A. Nicholas and Permutation
     
    Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
    Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.
    Input
    The first line of the input contains a single integer n (2 ≤ n ≤ 100) — the size of the permutation.
    The second line of the input contains n distinct integers a 1, a 2, ..., a n (1 ≤ a i ≤ n), where a i is equal to the element at the i-th position.
    Output
    Print a single integer — the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performing exactly one swap.
    Examples
    input
    Copy
    5
    4 5 1 3 2
    output
    Copy
    3
    input
    Copy
    7
    1 6 5 3 4 7 2
    output
    Copy
    6
    input
    Copy
    6
    6 5 4 3 2 1
    output
    Copy
    5
    Note
    In the first sample, one may obtain the optimal answer by swapping elements 1 and 2.
    In the second sample, the minimum and the maximum elements will be located in the opposite ends of the array if we swap 7 and 2.
    In the third sample, the distance between the minimum and the maximum elements is already maximum possible, so we just perform some unnecessary swap, for example, one can swap 5 and 2.






  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5. {
  6. int n; cin>>n;
  7. int a[n];int x;
  8. vector<pair<int,int>>v;
  9. for(int i=1;i<=n;i++)
  10. { cin>>x;
  11. v.push_back(make_pair(x,i));
  12.  
  13. }
  14. sort(v.begin(),v.end());
  15.  
  16. {
  17. int a=v[0].second;///5
  18. int b=v[n-1].second;///3
  19.  
  20. cout << max(max(n - b, b - 1), max(n - a, a - 1));
  21.  
  22.  
  23.  
  24. }
  25.  
  26.  
  27.  

Comments

Popular posts from this blog

Codeforce Problem 1703A. YES or YES?

Aptitude test assistant programmer 2018

1041A. Heist solution