确定数组是否可以旋转 3 个连续的数组元素进行排序?
determine if the array could be sorted rotating 3 consecutive array elements?
我有一个自然数序列的排列,从 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 次连续旋转对给定数组进行排序。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- 确定数组是否可以旋转 3 个连续的数组元素进行排序?
- 是数组中连续保存在内存中的元素
- 最大连续子数组(元素数量最多)