基于数组中移动元素的查询

Query based shifting elements in array

本文关键字:移动 元素 查询 于数组 数组      更新时间:2023-10-16

给定两个数字n和m。n表示数组中元素的数目,m表示查询的数目。我们有m个查询。我们需要对数组执行两种类型的查询。查询可以有两种类型,类型1和类型2。

TYPE 1查询表示为(1 i j):通过删除i到j位置之间的元素并将它们添加到前面来修改给定数组。

TYPE 2查询表示为(2i j):通过删除i到j之间的元素并将它们添加到后面来修改给定数组。

我们的任务是简单地在执行查询后打印数组[1]-数组[n]的差值,然后打印数组。


输入格式:第一行由两个空格分隔的整数n和m组成。第二行包含n个整数,表示数组的元素。M个查询紧随其后。每行包含一个类型1或类型2的查询,格式为(类型i j)。


输出格式:打印第一行的绝对值a[0]-a[n]。在第二行打印结果数组的元素。每个元素之间用一个空格隔开。

例子:
给定数组为[1,2,3,4,5,6,7,8]
执行查询(1 2 4)后,数组变成(2,3,4,1,5,6,7,8)。
执行查询(2 3 5)后,数组变成(2,3,6,7,8,4,1,5)。
执行查询(1 4 7)后,数组变成(7,8,4,1,2,3,6,5)。
执行查询(2 1 4)后,数组变成(2,3,6,5,7,8,4,1)。

对于这个问题,我编写了如下程序:
int main() 
{
int n,m;
cin>>n;
cin>>m;
int arr[n];
for(int i=0;i<n;i++)
{
    cin>>arr[i];
}
int count; // counter to control no of queries to accept
for(count=0;count<m;count++)
{
   int type,start,end; // 3 parts of query 
   cin>>type;cin>>start;cin>>end;
   if(type==1)
   { 
     //calculated difference between (start,end) to find no of iterations
     for(int i=0;i<=(start-end);i++)
     { // t is temporary variable
       int t=arr[(start-1)+i]; //(start-1) as index starts from 0
       arr[(start-1)+i]=arr[i];
       arr[i]=t;
     }
   }
   else
   {
      for(int i=0;i<=(start-end);i++)
     {
       int t=arr[(start-1)+i];
   // elements inserted from end so we subtract (n)-(start-end)
       arr[(start-1)+i]=arr[(n-1)-(start-end)+i];
       arr[(n-1)-(start-end)+i]=t;
     }
   }
   count++;
   //increment count
}
int absolute=abs(arr[0]-arr[n-1]);
cout<<absolute<<"n";
for(int i=0;i<n;i++)
{
  cout<<arr[i]<<" "<<endl;
}
return 0;
}

我希望代码能够正常工作,但令人惊讶的是,甚至没有正确显示输出。下面是测试用例:
输入:
8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4


预期输出:1
2 3 6 5 7 8 4 1


我的输出:7
1
2
3
4
5
6
7
8

我已经多次运行代码,但似乎无法理解问题从何而来。请查看代码并提供建议。

for循环条件错误。


正确方法:for (int i = 0;I<=(end - start);我+ +)