回文序列

来源:互联网 发布:执行 catmetx.sql脚本 编辑:程序博客网 时间:2024/06/05 09:08


如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列, 
{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。
现在给出一个数字序列,允许使用一种转换操作:
选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。

现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//利用递归,两端不论怎样都要相等或者最终合成为同一个数
#include <iostream>
usingnamespace std;
intcomb(int* nums, inthead, inttail) {
    inttimes = 0;
    intleft = nums[head], right = nums[tail];
    while(head < tail && left != right) {
        if(left < right) left += nums[++head], times++;
        elseright += nums[--tail], times++;
    }
    if(head >= tail) returntimes;
    elsereturn times += comb(nums, ++head, --tail);
}
intmain(){
    intn = 0;
    intnums[50] = {0};
    cin >> n;
    forinti = 0; i < n; i++)
        cin >> nums[i];
    cout << comb(nums, 0, n-1);
}

如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列, 
{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。
现在给出一个数字序列,允许使用一种转换操作:
选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。
现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。
0 0
原创粉丝点击