回文序列

题目描述
如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{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
输出

2

解法一
#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> &item,int head,int tail){
    int left = item[head],right = item[tail];
    int times = 0;
    while(head<tail&&left!=right){
        if(left<right){
            left += item[++head];
            ++times;
        }
        else{
            right += item[--tail];
            ++times;
        }
    }
    if(head>=tail){
        return times;
    }
    else
        return times+solve(item,++head,--tail);
}
int main1(){
    int n;
    while(cin>>n){
        vector<int> vec;
        for(int i = 0;i<n;i++){
            int a;
            cin>>a;
            vec.push_back(a);
        }
        cout<<solve(vec,0,n-1);
    }
    return 0;
}
解法二
#include <bits/stdc++.h>
using namespace std;
int solve1(int arr[], int n){
        int left = 0;
        int right = n - 1;
        int ans = 0;
        while (left < right){
            if (arr[left] < arr[right]){
                arr[left + 1] += arr[left];
                ++left;
                ++ans;
            }else if(arr[left] > arr[right]){
                arr[right - 1] += arr[right];
                --right;
                ++ans;
            }else{
                ++left;
                --right;
            }
        }
        return ans;
    }
int main(){
    int n;
    int a[1001];
    while(cin>>n){
        for(int i = 0;i<n;i++){
            int x;
            cin>>x;
            a[i] = x;
        }
        cout<<solve1(a,n);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值