codeforces 1005D

题目链接:https://codeforces.com/problemset/problem/1005/D

从前到后考虑每一个元素,当前元素一定是接在上一组连续的序列的末尾(或者是一个新数列的开头),
那么就设状态 (dp[i][0/1/2]) 表示以 i 结尾的模 3 余 0/1/2 的数字序列是否存在
如果已经可以整除 3 ,那么记录当前数列(贪心)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 200010; 

int n,ans;
int a[maxn],sum[maxn],dp[maxn][3]; // dp[i] 表示包含第 i 个数字的连续序列, 是否模 3 余 0/1/2
char s[maxn]; 

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	ans = 0;
	scanf("%s",s+1);
	n = strlen(s+1);
	
	for(int i=1;i<=n;++i) a[i] = s[i] - '0';
	
	int f = 0;
	for(int i=1;i<=n;++i){
		int rem = a[i] % 3;
	
		dp[i][(0+rem)%3] = dp[i-1][0];
		dp[i][(1+rem)%3] = dp[i-1][1];
		dp[i][(2+rem)%3] = dp[i-1][2];
		dp[i][rem] = 1;
		
//		printf("%d: %d %d %d
",i,dp[i][0],dp[i][1],dp[i][2]);
		if(dp[i][0]){
			++ans;
			dp[i][0] = 0, dp[i][1] = 0, dp[i][2] = 0;
		}
	}
	
	printf("%d
",ans);
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13825934.html