One-by-one to solve the Sequence Problem (2)

本文探讨了一个涉及整数数组的问题,即通过删除相邻且和为奇数的元素来尽可能缩短序列,目标是最小化最终序列的长度。文章提供了一个具体实例,并给出了一段C++代码示例,用于解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#1399 : Shortening Sequence (from hihocoder) Stack

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

There is an integer array A1, A2 …AN. Each round you may choose two adjacent integers. If their sum is an odd number, the two adjacent integers can be deleted.

Can you work out the minimum length of the final array after elaborate deletions?

输入

The first line contains one integer N, indicating the length of the initial array.

The second line contains N integers, indicating A1, A2 …AN.

For 30% of the data:1 ≤ N ≤ 10

For 60% of the data:1 ≤ N ≤ 1000

For 100% of the data:1 ≤ N ≤ 1000000, 0 ≤ Ai ≤ 1000000000

输出

One line with an integer indicating the minimum length of the final array.

样例提示

(1,2) (3,4) (4,5) are deleted.

样例输入

7
1 1 2 3 4 4 5

样例输出

1

Code Snippet

#define LOG(x) cout << #x << " = " << (x) << endl
#define PRINTLN(x) cout << (x) << endl
#define MEM(x, y) memset((x), (y), sizeof((x)))
#include <bits/stdc++.h>
using namespace std;
const double PI = 2*acos(0);
typedef long long ll;
typedef complex<double> Complex;
int nextInt()
{
    int x;
    scanf("%d", &x);
    return x;
}
ll nextLL()
{
    ll x;
    scanf("%lld", &x);
    return x;
}
//TEMPLATE

//MAIN
int main()
{
    //freopen("in.txt", "r", stdin);
    int n;
    while (scanf("%d", &n) != EOF) {
         stack<ll> s;
    int ans = 0;
    for (int i = 0; i < n; i++) {
      ll t = nextLL();
      if (!s.empty() && (s.top() + t) % 2) {
            s.pop();
            ans += 2;
          } else s.push(t);
        }
        PRINTLN(n - ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值