【问题标题】:Query based shifting elements in array数组中基于查询的移位元素
【发布时间】:2016-12-26 18:49:34
【问题描述】:

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

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

TYPE 2 查询表示为 (2 i 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

我多次试运行代码,但似乎无法理解问题出在哪里。请查看代码并提供建议。

【问题讨论】:

  • std::rotate 会有所帮助。
  • 你能告诉我修改我的代码吗?感谢您的痛苦。

标签: c++ arrays algorithm


【解决方案1】:

for循环条件错误。


正确方法:for (int i = 0; i

【讨论】:

  • 我更正了代码,但它仍然不起作用。答案错了 2 个数字,输出格式显示新行,我无法理解。
猜你喜欢
  • 2021-11-24
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2018-08-15
  • 1970-01-01
相关资源
最近更新 更多