CF1930D1 - Sum over all Substrings (Easy Version)

对于每一个 f(i,j),我们考虑如何计算。我们发现,1010 式的字符串很有用,所以这启发我们如果遇到了一个模式 pi='1',那么我们可以在 i+1 的位置放一个 '1'。这样我们直接处理了 i,i+1,i+2。容易证明这是最优的。

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

const int N = 3e5 + 7;

int read() {
    char c = getchar();
    int x = 0, p = 1;
    while ((c < '0' || c > '9') && c != '-') c = getchar();
    if (c == '-') p = -1, c = getchar();
    while (c >= '0' && c <= '9')
        x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    return x * p;
}

int n;
string s;

int f(string p) {
	int res = 0;
	for (int i = 0; i < (int) p.size(); i ++) {
		if (p[i] == '1') {
			res ++;
			i += 2;
		}
	}
	return res;
}

void solve() {
	n = read();
	cin >> s; long long ans = 0;
	for (int i = 0; i < n; i ++) {
		string t = "";
		for (int j = i; j < n; j ++) {
			t += s[j];
			ans += f(t);
		}
	}
	cout << ans <<'\n';
}

signed main() {
	int t = read();
	while (t --) solve();
	return 0;
}

作者:DE_aemmprty

出处:https://www.cnblogs.com/aemmprty/p/18090518

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   DE_aemmprty  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示