Codeforces round #259 (Div. 2) (sequence)

Source: Internet
Author: User

Link: http://codeforces.com/contest/454/problem/ B


B. Little Pony and sort by shifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output

One day, Twilight Sparkle is interested in how to sort a sequence of IntegersA1 ,?A2 ,?...,?ANIn non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:

A1 ,? A2 ,?...,? A N? →? A N,? A1 ,? A2 ,?...,? A N? -? 1.

Help Twilight Sparkle to calculate: What is the minimum number of operations that she needs to sort the sequence?

Input

The first line contains an integerN(2? ≤?N? ≤? (105). The second line containsNInteger numbersA1 ,?A2 ,?...,?AN(1? ≤?AI? ≤? 105 ).

Output

If it's impossible to sort the sequence output-1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

Sample test (s) Input
22 1
Output
1
Input
31 3 2
Output
-1
Input
21 2
Output
0

Ideas:

Judge whether there are several "downhill", that is, the number behind is smaller than the previous one;

If no value exists, 0 is output. If more than one value exists,-1 is output. If there is one, the relationship between a [1] and a [n] needs to be determined;


The Code is as follows:

#include <cstdio>#include <cstring>int main(){int n;int i, j;int a[100017];while(~scanf("%d",&n)){for(i = 1; i <= n; i++){scanf("%d",&a[i]);}int cont = 0;int t;for(i = 2; i <= n; i++){if(a[i] < a[i-1]){cont++;t = i;}}if(cont == 0)printf("0\n");else if(cont > 1)printf("-1\n");else if(cont == 1 && a[n] <= a[1])printf("%d\n",n-t+1);elseprintf("-1\n");}return 0;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.