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--);
    }
    

     

  • 相关阅读:
    nginx 配置详解
    ngnix 负载均衡
    nginx 安装搭建与配置介绍
    11.15java实习生面试总结
    笔试题:编写一个用户注册接口
    java第一次笔试+面试总结
    《啊哈算法》读后总结(下)
    java常见排序算法
    Tomcat安装及配置教程
    算法题:购买n个苹果,苹果6个一袋或者8个一袋,若想袋数最少,如何购买?
  • 原文地址:https://www.cnblogs.com/helloworldcode/p/6616963.html
Copyright © 2011-2022 走看看