Sort the Array
Posted 啦啦啦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.
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[i]?≤?109).
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.
3
3 2 1
yes
1 3
4
2 1 3 4
yes
1 2
4
3 1 2 4
no
2
1 2
yes
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的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 258B Sort the Array
js代码片段: utils/lcoalStorage/cookie
环境初始化 Build and Install the Apache Thrift IDL Compiler Install the Platform Development Tools(代码片段