E1. Array and Segments (Easy version)

题目:

 

样例:

输入
3
3
120
5
11011
6
600005

输出
3
6
1

 

题意:

        题目意思是,找出有该数组中,有多少个子数组是   元素之和等于该子数组长度

思路:

        在这里,我们可以弄个偏移量 -1 ,

比如 当 子数组a 为  a = 【1】    那么  1 - 1 == 0   则  sum = 1 - 1 = 0  当 sum == 0 的时候ans++

反之不是。

代码详解如下:

#include <iostream>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;
umap<int, int>r;	// 记录 每个子数组中

inline void solve()
{
	r.clear();
	string s;
	int n, ans = 0;
	cin >> n;
	getchar();
	getline(cin, s);
	int sum = 0;
	for (int i = 0; i < n; ++i)
	{
		// 这里是记录该数组是否满足 sum == 0
		// 即满足数组元素之和等于数组长度
		sum += (s[i] - '0' - 1);

		// 如果满足 ans++
		if (!sum)
			ans++;

		// 累加子数组满足 sum == 0 的
		ans += r[sum];

		// 记录满足子数组个数
		++r[sum];
	}
	cout << ans << endl;
}


signed main()
{
//	freopen("a.txt", "r", stdin);
//	___G;
	int _t = 1;
	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

最后提交:

​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值