CF1428F-Fruit Sequences

题目链接https://codeforces.com/contest/1428/problem/F
参考题解https://www.cnblogs.com/zkyJuruo/p/13833960.html
OI爷,永远滴神!
思路
对于01字符串从右向左遍历,如果当前 s [ i ] = 0 s[i]=0 s[i]=0,那么对序列没有任何贡献,如果 s [ i ] = 1 s[i]=1 s[i]=1,如果出现连续的1,设在第i位该值为 h [ i ] h[i] h[i],那么从当前位到上一次出现 h [ i ] h[i] h[i]之间的值,需要全部加上1 。例举一个样例就是110011,如果此时 i = 2 i=2 i=2,那么从 [ 2 , 4 ] [2,4] [2,4]这一段范围,它的结果就会+3,而 [ 5 , 6 ] [5,6] [5,6]的代价还是不变的。如果 i = 1 i=1 i=1,那么从 [ 1 , 5 ] [1,5] [1,5]的范围之内代价都会+1,结果就是+5。由此看来就只要看当前出现的 h [ i ] h[i] h[i]的这个值,在上一次所出现的位置在哪里,那么代价就会增加 h [ i ] − i h[i]-i h[i]i,如果不存在这样的位置,那么代价就相当于直接加上 n − i + 1 n-i+1 ni+1
开一个pos数组记录每一个h[i]最后出现的位置。因为在连续求1的过程中,其最后的位置恰好是反一反的,例如110011,h[5]=2,h[6]=1,但是在遍历到位置2的时候,h[2]=1所对应1应该是第5位,h[1]=2所对应的位置应该是第6位,所以在发现s[i]=0 && s[i+1]=1的时候,要把pos数组的一部分reverse一下。
代码

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
#define int LL
typedef pair<int, int> PII;
const int inf = 0x3f3f3f3f;
const int N = 5e5 + 10;
const int mod = 1e9 + 7;

char s[N];
int pos[N], h[N];

void solve() {
    int n;
    scanf("%lld%s", &n, s + 1);
    int res = 0, sum = 0;

    for(int i = n; i; i--) {
        h[i] = s[i] == '0' ? 0 : h[i + 1] + 1;
        if(s[i] == '1') {
            if(!pos[h[i]]) sum += n - i + 1;
            else sum += pos[h[i]] - i;
            pos[h[i]] = i;
        }
        else if(s[i] == '0' && s[i + 1] == '1') {
        	int x = h[i + 1];
        	reverse(pos + 1, pos + 1 + x);
        }
        res += sum;
        // printf("i = %d sum = %d\n", i, sum);
    }
    printf("%lld\n", res);
}

signed main() {
    // freopen("in.txt", "r", stdin);
    // int t; cin >> t; while(t--)
    solve();
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值