首先发出题目链接:
链接:https://ac.nowcoder.com/acm/contest/884/K
来源:牛客网
涉及:思维
点击这里回到2019牛客暑期多校训练营解题—目录贴
题目如下:
代码如下
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
int num[maxn];
int mod[5];
ll len[maxn];
string a;
ll ans = 0;
int main(){
cin >> a;
int n = a.size();
for(int i = 0; a[i]; i++){
num[i+1] = a[i] - '0';
}
mod[0] = 1;
int cnt = 0;
for(int i = n; i >= 1; i--){
if(num[i] == 0){
cnt++;
if(i-1 == 0 || num[i-1] != 0){
len[i] = cnt;
ans += 1ll * (1 + cnt) * cnt / 2;
}
}else{
cnt = 0;
}
}
for(int i = 1; i <= n; i++){
if(num[i] == 0 && len[i]){
if(len[i] >= 2 && i - 1 > 0){
ans += 1ll * (mod[num[i-1]] - 1) * (len[i] - 1);
}
}
num[i] = (num[i] + num[i-1]) % 3;
mod[num[i]]++;
}
cout << ans;
return 0;
}