D1 - Painting the Array I

题意:
将序列从左到右依次加入到两个集合中的一个,使得最后的结果最小。
思路:
遍历序列,将数字依次存入队列,再未遇到相邻两数相同的情况下先按兵不动,依据此后情况再做操作有利无害。
当第一次出现相邻两数相同时,此时两集合为空。
此时 a[pos] == a[pos - 1] 并且 pos - 1 之前无相邻两数相同。
这时最优操作可为: 将 [1, pos - 1] 放入某一集合,将 pos 单独放入另一集合,即将 pos 与 pos - 1 分开放置,使得贡献为区间长度。如若不分开放置,则当前贡献减一,使得之后贡献最多加一,所以选择前者。
设当前两集合的末尾元素是 x。
当遍历到 a[i], 此时队列为空,但是 a[i] == x 时,只能将 a[i] 放入任意集合,贡献为0,末尾元素依然为 x。
当再次遇到相邻两数相同时,思考此时能进行的操作:
设此时队列对应的原区间为 [l, r] a[r] == a[r - 1]。
a[r] == x.
1.假如队列中存在相邻两数都不等于 x, 设 a[pos] != x && a[pos + 1] != x 那么可以将 [l, pos] 放在某一集合(a[l] 一定不等于 x),将[pos + 1, r - 2] 放置在某一集合,再将[r - 1, r]分开放置到两集合中,贡献为区间长度,集合末尾依然为 x。
2.假若不存在相邻两数都不等于x,无论怎么放置,贡献最高都为区间长度减一,并且集合末尾依然为 x。
a[r] != x.
此时将 [l, r - 1] 放置在某一集合,r 单独放置于某一集合即可,贡献为区间长度,集合末尾为 a[r]。
在第一种情况中,需要记录队列中是否存在相邻两数都不等于 x,为了方便,不妨设集合刚开始为空时末尾元素都为 0。
重复操作,直到遍历完序列为止,此时队列剩余的元素也能算进贡献。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <set>
#include <string>
#include <queue>
#include <map>
#include <stack>
#include <map>
#include <unordered_map>
#include <vector>
#include <cmath>
//#include <ext/rope>
//#include <bits/stdc++.h> 

using namespace std;

#define gt(x) x = read()
#define int long long
#define ios ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define endl "\n"
//#define x first
//#define y second

int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0}; 

//typedef __int128 INT;
typedef pair<double, int> PDI;
typedef pair<int, int> PII;
typedef unsigned long long ULL;

inline int read(int out = 0)
{
    char c;
    while((c=getchar()) < 48 || c > 57);
    while(c >= 48 && c <= 57) out=out*10+c-48,c=getchar();
    return out; 
}

const int N = 1e5 + 10;
const int M = N * N;
const int mod = 1e9 + 7;
const int PP = 131;
const int inf = 0x3f3f3f3f;
const int INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-10;
const double PI = acos(-1);

int n;
int a[N];
int q[N], hh = 0, tt = -1;

signed main(){
	scanf("%lld", &n);
	
	for (int i = 1; i <= n; i ++)   scanf("%lld", &a[i]);
	
	int b = 0, res = 0;
	bool add = true;
	
	for (int i = 1; i <= n; i ++){
		if (hh > tt && a[i] == b)    continue;
		
		q[++ tt] = a[i];
		
		if (hh < tt && q[tt] != b && q[tt - 1] != b)   add = true;
		if (hh < tt && q[tt] == q[tt - 1]){
			res += tt - hh + add;
			add = false;
			b = q[tt];
			tt = -1;
		}
	} 
	
	res += tt - hh + 1;
	
	cout << res << endl;
	
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值