算法基础:一维前缀和

算法:前缀和

#include <bits/stdc++.h>

using namespace std;
const int N = 1e5 + 10;

int a[N], s[N];  //s[N]前缀和数组 s[i] = a[1] + a[2] + a[3] + ...+ a[i]
int main(){
	int n, m;
	cin >> n >> m;
	for(int i = 1; i <= n; i++){
		cin >> a[i];
	}
	
	for(int i = 1; i <= n; i++){  //前缀和公式:s[n] = s[n-1] + a[n]
		s[i] = s[i - 1] + a[i];
	}
	
	while(m--){
		int l, r;
		cin >> l >> r;
		
		cout << s[r] - s[l - 1] << endl;  //[l~r]的前缀和公式:s[r] - s[l-1]
	}
	
	
	return 0;
}

div.3 D. Black and White Stripe(前缀和)

思路:
题意: 给定长度为\(n\)的字符串,只有\(W\)\(B\)两个字符,分别表示白色和黑色,我们可以将白色修改成黑色,记作修改一次,求为了获得长度为\(K\)的连续黑色,最少要修改多少个白色。
题解:
从头枚举每一个长度为\(k\)的子字符串,查询该子字符串中白色的个数,个数取\(min\),就是\(ans\)。而快速找到子字符串中白色的个数,就可以通过前缀和预处理出来。

#include<bits/stdc++.h>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define bug(x) cout<<#x<<"=="<<x<<endl;
#define endl "\n"
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int inf = 0xc0c0c0c0;

const int N = 2e5 + 10;
int a[N];
void solve() {
	int n, k;
	cin >> n >> k;
	string s;
	cin >> s;
	s = " " + s;
	for (int i = 1; i <= n; i++) {
		if (s[i] == 'W') {
			a[i] = a[i - 1] + 1;
		} else {
			a[i] = a[i - 1];
		}
	}

	int ans = INF;
	for (int i = k; i <= n; i++) {
		ans = min(ans, a[i] - a[i - k]);
	}
	cout << ans << endl;
}

int main() {
	ios;
	int t;
	cin >> t;
	while (t--) {
		solve();
	}
	return 0;
}
posted @ 2022-11-25 10:58  csai_H  阅读(41)  评论(0)    收藏  举报