题目:
如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列,{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。
现在给出一个数字序列,允许使用一种转换操作:
选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。
现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。
输入描述:
输入为两行,第一行为序列长度n ( 1 ≤ n ≤ 50) 第二行为序列中的n个整数item[i] (1 ≤ iteam[i] ≤ 1000),以空格分隔。
输出描述:
输出一个数,表示最少需要的转换次数
输入例子1:
4 1 1 1 3
输出例子1:
2分析:
使用vector存贮序列,通过首尾迭代器分别提取首尾元素进行比较,将较小的一方相邻元素相加,并存储于当前位置,若两元素相等则抛弃两元素。
需要注意迭代器的使用,end迭代器指向尾后元素,故需要比较(*beg)和*(end-1),同时迭代器移动时也需要小心。
#include <iostream>
#include <vector>
using namespace std;
int revert(vector<int> &arr)
{
int count = 0;
for(auto beg = arr.begin(), end = arr.end(); beg < end;)
{
if((*beg) < *(end - 1))
{
*(beg + 1) = *beg + *(beg + 1);
++beg;
++count;
}
else if((*beg) > *(end - 1))
{
*(end - 2) = *(end - 1) + *(end - 2);
--end;
++count;
}
else
{
++beg;
--end;
}
}
return count;
}
int main()
{
int n, temp, count;
vector<int> arr;
cin >> n;
for(int i = 0; i < n; ++i)
{
cin >> temp;
arr.push_back(temp);
}
count = revert(arr);
cout << count;
return 0;
}