回文序列

回文序列

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

 

#include<stdio.h>
#include<iostream>
using namespace std; 
/*
 *head:代表数组的起始索引,tail代表数组的最后一个元素的索引
 *对于数字序列,分别使用两个索引(头索引head和尾索引tail),
 *如果可以构造成回文数字,则head和tail分别向中间靠,
 *即head与它右边的数字求和,tail和它左边的数字求和。
 */
int hand(int a[],int head,int rear);
int main()
{
	int n,a[100];  
	int i;
	printf("请输入你要输入的数字个数\n");
    cin>>n;
	printf("请分别输入,按回车树下一个数字\n");
    for(i=0;i<n;i++)
		cin>>a[i];
	int count=hand(a,0,n-1);
	printf("要处理的次数为:%d\n",count);
    return 0;
}
int hand(int a[],int head,int rear){
	int left=a[head];
	int right=a[rear];
	int times=0;
	while(head<rear && left!=right){
		if(left<right){
			left+=a[++head];		
		}
		else
			right+=a[--right];
		times++;
	}
	if(head>=rear-1)
		return times;
	else
		return times+hand(a,head++,rear--);
}

 

 

posted @ 2017-03-25 13:44  晓乎  阅读(2089)  评论(0编辑  收藏  举报
总访问: counter for blog 次