Sort the Array
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.
Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a
The first line of the input contains an integer n (1?≤?n?≤?105) — the size of array a.
The second line contains n distinct space-separated integers: a[1],?a[2],?...,?a[n] (1?≤?a
Print "yes" or "no" (without quotes), depending on the answer.
If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.
3output Copy
3 2 1
yesinput Copy
1 3
4output Copy
2 1 3 4
yesinput Copy
1 2
4output Copy
3 1 2 4
noinput Copy
2output Copy
1 2
yesNote
1 1
Sample 1. You can reverse the entire array to get [1,?2,?3], which is sorted.
Sample 3. No segment can be reversed such that the array will be sorted.
Definitions
A segment [l,?r] of array a is the sequence a[l],?a[l?+?1],?...,?a[r].
If you have an array a of size n and you reverse its segment [l,?r], the array will become:
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].
題解:因為是n個不同的數,所以先哈希一下。哈希的好處是找需要反轉的序列的左端點和右端點時操作簡單一點:i != Hash[a[i]]。然後再檢查一下就行了。
個人認為:hash後寫起方便一點。
1 #pragma warning(disable:4996) 2 #include<cmath> 3 #include<map> 4 #include<vector> 5 #include<cstdio> 6 #include<cstring> 7 #include<iostream> 8 #include<algorithm> 9 using namespace std; 10 11 const int maxn = 100005; 12 13 int n; 14 int a[maxn], b[maxn]; 15 16 int main() 17 { 18 while (cin >> n) { 19 for (int i = 1; i <= n; i++) { 20 cin >> a[i]; 21 b[i] = a[i]; 22 } 23 map<int, int>p; 24 sort(a + 1, a + n + 1); 25 for (int i = 1; i <= n; i++) p[a[i]] = i; 26 int L = -1, R = -1; 27 for (int i = 1; i <= n; i++) if (p[b[i]] != i) { L = i; break; } 28 for (int i = n; i >= 1; i--) if (p[b[i]] != i) { R = i; break; } 29 if (L == -1 && R == -1) { 30 printf("yes\n1 1\n"); 31 continue; 32 } 33 bool flag = true; 34 for (int i = L + 1; i <= R; i++) if (b[i - 1] < b[i]) { flag = false; break; } 35 if (flag) { 36 printf("yes\n%d %d\n", L, R); 37 } 38 else { 39 printf("no\n"); 40 } 41 } 42 return 0; 43 }
Sort the Array