我有一个从1开始递增的自然数序列的排列,现在作为一个数组给出。如何判断这个数组能否通过旋转其中连续的3个元素来排序?
我已经实现了一个算法,基本上是将数组的索引与该索引处的元素进行比较。如果它们不相等,则调用choose_indices()函数,在数组中找到要交换的元素的正确位置后,选择包含待交换数字的3个连续元素并将其旋转。对于大小为n的数组,经过n-1次旋转后,数组就被排序了。如果数组可以使用3个连续元素旋转进行排序,此实现将返回true,但如果无法使用此方法对数组进行排序则会超时。
我已经实现了一个算法,基本上是将数组的索引与该索引处的元素进行比较。如果它们不相等,则调用choose_indices()函数,在数组中找到要交换的元素的正确位置后,选择包含待交换数字的3个连续元素并将其旋转。对于大小为n的数组,经过n-1次旋转后,数组就被排序了。如果数组可以使用3个连续元素旋转进行排序,此实现将返回true,但如果无法使用此方法对数组进行排序则会超时。
using namespace std;
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstring>
int n;
void rotate(vector<int> &arr,int end,int mid,int start)
{
int temp=arr[start];
arr[start]=arr[end];
arr[end]=arr[mid];
arr[mid]=temp;
}
void choose_indices(vector<int> &arr,int s,int q)
{
for(int l=q;l<n;l++)
{
if(arr[l]==s)
{
if(l-q>=2)
{
rotate(arr,l,l-1,l-2);
break;
}
else
{
rotate(arr,l+1,l,l-1);
break;
}
}
}
}
int main()
{
vector<int> arr;
int q,count=0;
cin>>q;
for(int i=0;i<q;i++)
{
cin>>n;
count=0;
for(int i=0,p;i<n;i++)
{
cin>>p;
arr.push_back(p);
}
for(int j=0,k=1;j<n && k<n; )
{
if(arr[j]!=k)
{
choose_indices(arr,k,j);
if(arr[j]==k)
{
j++;
k++;
count++;
}
}
else
{
j++;
k++;
count++;
}
}
if(count==n-1)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
arr.clear();
}
}
示例输入: 1 2 3 5 4
针对此输入,我的代码出现了运行时错误。 如何判断给定的数组是否无法使用连续3个元素的旋转进行排序?
1 5 1 2 3 5 4
不是“自然数序列的排列”。 - Igor Tandetnik