zoukankan      html  css  js  c++  java
  • 回文序列

    回文序列

    如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
    {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("请输入你要输入的数字个数
    ");
        cin>>n;
    	printf("请分别输入,按回车树下一个数字
    ");
        for(i=0;i<n;i++)
    		cin>>a[i];
    	int count=hand(a,0,n-1);
    	printf("要处理的次数为:%d
    ",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--);
    }
    

     

  • 相关阅读:
    python常用包收集
    python pep 8
    常用python字符串处理
    安全资源整理
    WordPress下载安装简单配置实例
    PHP框架学习之Laravel基本功能
    PHP框架学习之Laravel安装
    PHP面试题之优化
    PHP面试题之小杂鱼
    PHP面试题之文件目录操作
  • 原文地址:https://www.cnblogs.com/helloworldcode/p/6616963.html
Copyright © 2011-2022 走看看