给定一个长度为n的整数数组a,元素均不相同,问数组是否存在这样一个片段,只将该片段翻转就可以使整个数组升序排列。其中数组片段[l,r]表示序列a[l], a[l+1], ..., a[r]。原始数组为
a[1], a[2], ..., a[l-2], a[l-1], a[l], a[l+1], ..., a[r-1], a[r], a[r+1], a[r+2], ..., a[n-1], a[n],
将片段[l,r]反序后的数组是
a[1], a[2], ..., a[l-2], a[l-1], a[r], a[r-1], ..., a[l+1], a[l], a[r+1], a[r+2], ..., a[n-1], a[n]。
Input
The first line of data is an integer: n (1≤n≤105), which indicates the length of the array. The second line of data is n integers a [1], a [2], ..., a [n] (1≤a [i] ≤109).
|
Sample input 4 2 1 3 4 |
Output
Output "yes" if it exists; otherwise output "no" without quotation marks.
|
Sample output
yes
|
Time limit C / C ++ language: 1000MS Other languages: 3000MS |
Memory limit C / C ++ language: 65536KB Other languages: 589824KB |
Code directly:
#include <iostream>
using namespace std;
bool rotateArray(int *ar, int n){
if(n == 1) return true;
int pos1 = -1, pos2 = -1;
bool flag = false;
for (int i = 0; i < n - 1 ; ++i) {
if(ar[i] > ar[i+ 1] && !flag){
pos1 = i;
flag = true;
}
if(ar[i] < ar[i +1] && flag){
pos2 = i;
break;
}
}
for (int j = 0; j <= (pos2 - pos1)/2; ++j) {
int tmp = ar[pos1 + j];
ar[pos1 + j] = ar[pos2 - j];
ar[pos2 - j] = tmp;
}
for (int k = 0; k < n - 1; ++k) {
if(ar[k] > ar[k + 1]) return false;
}
return true;
}
int main() {
int n;
cin >> n;
int ar[n];
for (int i = 0; i < n; ++i) {
cin >> ar[i];
}
if(rotateArray(ar, n)) cout << "yes" << endl;
else cout << "no" << endl;
return 0;
}