Codeforces Round #700 (Div. 2)D1 - Painting the Array I

传送门
一、题意: 将数组a分为0和1两个部分,分类完后需要分别将相邻的相同元素合并,合并后统计个数相加,要求总和达到最大值。
二、思路: 可以开两个栈s1,s2,正常分类方法就是s1放一个然后s2放一个,如果遇到跟栈顶相同的就要特判然后放到另外一个栈中。
但是还有一种情况要注意:可能a[i]与s1的栈顶不同但是a[i+1],a[i+2]与s1的栈顶相同,但是根据上面的轮换规则该轮应将a[i]放在s2中,如果这样做可能会导致a[i+1]与s1栈顶合并,就会导致种类减少,所以需要特判。
cpp代码

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<cmath>
#include<map>
#define ll long long
using namespace std;
const int MAXN = 100005;
int a[MAXN];
stack<int>s1, s2;
int main()
{
	//std::ios::sync_with_stdio(0);
	int n;
	scanf("%d", &n);
	int flag = 1;
	for (int i = 1; i <= n; i++)scanf("%d", &a[i]);
	for (int i = 1; i <= n; i++) {
		if (s1.empty())s1.push(a[i]);
		else if (flag) {
			if (!s2.empty()&&a[i] == s2.top())s1.push(a[i]);
			else {
				if (a[i + 1] == s1.top())s1.push(a[i]);
				else {
					s2.push(a[i]);
					flag = 0;
				}
			}
		}
		else {
			if (!s1.empty()&&a[i] == s1.top())s2.push(a[i]);
			else {
				if (a[i + 1] == s2.top())s2.push(a[i]);
				else {
					s1.push(a[i]);
					flag = 1;
				}
			}
		}
	}
	int x = 0, next = 0;
	flag = 1;
	ll ans = 0;
	while (!s1.empty()) {
		x = s1.top();
		s1.pop();
		if (flag) {
			ans++;
			flag = 0;
		}
		else if (x != next)ans++;
		next = x;
	}
	flag = 1, next = 0;
	while (!s2.empty()) {
		x = s2.top();
		s2.pop();
		if (flag) {
			ans++;
			flag = 0;
		}
		else if (x != next)ans++;
		next = x;
	}
	printf("%lld", ans);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值