[CF909D]Colorful Points

题目

传送门 to CF

传送门 to VJ

思路

感谢@太阳星人FxxL 的博客提供了思路。

模拟。唯一需要的优化,就是将连续的同一种颜色压缩成一段。

为什么可以呢?这样一来,每次你 O ( 1 ) \mathcal O(1) O(1) 的访问一个颜色段的时候,至少会被删掉一个点。

于是总复杂度就是点数 O ( n ) \mathcal O(n) O(n)

代码

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
inline int readint(){
	int a = 0; char c = getchar(), f = 1;
	for(; c<'0' or c>'9'; c=getchar())
		if(c == '-') f = -f;
	for(; '0'<=c and c<='9'; c=getchar())
		a = (a<<3)+(a<<1)+(c^48);
	return a*f;
}
inline void writeint(long long x){
	if(x < 0) putchar('-'), x = -x;
	if(x > 9) writeint(x/10);
	putchar((x%10)^48);
}
# define MB template < class T >
MB void getMax(T &a,const T &b){ if(a < b) a = b; }
MB void getMin(T &a,const T &b){ if(b < a) a = b; }

struct Node{
	int color, len;
	Node* nxt;
	Node(int C,int L):color(C),len(L){
		nxt = nullptr;
	}
};
Node* head;

bool connect(Node* &a){
	Node* b = a->nxt;
	if(a->color != b->color)
		return false;
	a->len += b->len, a->nxt = b->nxt;
	delete b; return true;
}

char s[1000005];
# define Continue(x) do{ x = x->nxt; }while(false)
int main(){
	scanf("%s",s); int n = strlen(s);
	Node* now = (head = new Node(s[0],1));
	for(int i=1; i<n; ++i){
		now->nxt = new Node(s[i],1);
		if(not connect(now))
			Continue(now);
	}
	int ans = 0;
	while(head != nullptr){
		if(head->nxt == nullptr) break;
		++ ans, now = head;
		while(now->nxt != nullptr){
			-- now->nxt->len;
			if(now->nxt->nxt != nullptr)
				-- now->nxt->len;
			if(now->nxt->len <= 0)
				Continue(now->nxt);
			else Continue(now);
		}
		-- head->len;
		if(head->len <= 0)
			Continue(head);

		now = head;
		while(now != nullptr){
			if(now->nxt == nullptr) break;
			if(not connect(now)) Continue(now);
		}
	}
	printf("%d\n",ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值