确定数组是否可以旋转 3 个连续的数组元素进行排序?

determine if the array could be sorted rotating 3 consecutive array elements?

本文关键字:数组元素 连续 排序 数组 是否 旋转      更新时间:2023-10-16

我有一个自然数序列的排列,从 1 开始递增为数组。如何确定数组是否可以使用 3 个连续元素的旋转进行排序?

我已经实现了一个算法,其中基本上我将数组的索引与数组中该索引处的元素进行比较。如果它们不相等,那么我调用函数 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 个连续元素的旋转进行排序?

旋转 3 个相邻元素将始终取消 2 次反转(如果存在(,否则将引入 2 次反转

考虑一下:

1 2 3 5 4

只有 1 个反转,无论你旋转多少次,你永远无法在不引入其他反转的情况下取消该反转,因为你将始终旋转 3 个连续的元素

因此,只需计算反转的数量,如果它是奇数,那么答案是否定的,否则为是。有有效的算法来计算反转的数量(如合并排序(。

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);
}
//Counting the number of inversion in the array
int ctiv=0;
for(int r=0;r<n;r++)
{
for(int s=r+1;s<n;s++)
{
if(arr[r]>arr[s] && r<s)
{
ctiv++;
}
}
}
if(ctiv%2!=0)
{
cout<<"NO"<<endl;
}
else 
{
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;
}
arr.clear();
}
}
}

这是我设计的算法,它发现给定的算法是否可以排序,如果可以排序,它通过执行必要的 3 次连续旋转对给定数组进行排序。