Vasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to rinclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that the segment's endpoints did not coincide. For example, if n = 8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... n using exactly one segment reversal. If it is possible, find the segment itself.
The first line contains an integer n (1 ≤ n ≤ 1000) which is the number of coins in Vasya's collection. The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time.
If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l r(1 ≤ l < r ≤ n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 ... n the given one.
思路分析:
由题意可知,从左往右,如果ai等于i(i下标从1开始),说明其没被交换;从右往左也是如此。
于是设置两个坐标,分别从左右开始检测,知道不相符。
检测之间一段是否满足相邻两数差1的大小关系。
代码如下:
#include <iostream>
using namespace std;
int left_x,right_x;//左右坐标位置
int n;
int a[1001];
bool check()
{
left_x=1;
while(left_x<=n&&a[left_x]==left_x) left_x++;//左光标移动
right_x=n;
while(right_x>=1&&a[right_x]==right_x) right_x--;//右光标移动
if(left_x>=n) return false;
for(int i=left_x;i<right_x;i++)//检查递减关系
if(a[i]!=a[i+1]+1) return false;
return true;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
if(check()) cout<<left_x<<" "<<right_x<<endl;
else cout<<"0 0"<<endl;
}