Sha-1611 Crane reasoning + greedy
Enter a 1-n sequence, which must be transformed into a sequence after operation. The operation rules are as follows:
During each operation, you can select a continuous interval with an even length and swap the first half and the last half.
Tip: 2n operation is enough.
Solution: This prompt is critical. 2n operations indicate that up to two operations are required for each number.
The operation should be performed from left to right, and the previous number should be settled first, so you can skip the previous number.
Assume that the operation is at the position I, and the number I is at the position pos. Now we need to determine whether I can be directly transferred to the position I after the operation.
If I + (pos-I) * 2-1 <= n, the operation can be completed at one time.
If the above conditions are not true, there are two situations:
One is that the distance between pos and I is odd: You can directly exchange the value of [I, pos ].
If the distance is an even number, replace the value of [I + 1, pos ].
Refer to other people's code:
#include
#include#include
#include
using namespace std;typedef pair
Pair;#define maxn 10010int num[maxn];void change(int l, int r) { for(int i = l, j = l + (r - l + 1) / 2; j <= r; j++, i++) swap(num[i],num[j]);}int main() { int test, n; scanf("%d", &test); while(test--) { scanf("%d", &n); for(int i = 1 ; i <= n; i++) scanf("%d", &num[i]); vector
> ans; for(int i = 1; i <= n; i++) { int pos; for(int j = i; j <= n; j++) if(num[j] == i) { pos = j; break; } if(pos == i) continue; if(i + 2 * (pos - i) - 1 <= n) { ans.push_back(Pair(i,i + 2 * (pos - i) - 1)); change(i, i + 2 * (pos - i) - 1); } else { if((pos - i) % 2) { ans.push_back(Pair(i, pos)); change(i,pos); } else { ans.push_back(Pair(i + 1, pos)); change(i + 1, pos); } i--; } } cout << ans.size() << endl; for(int i = 0; i < ans.size(); i++) printf("%d %d\n",ans[i].first, ans[i].second); } return 0;}