其他分享
首页 > 其他分享> > [tdog]最长子串

[tdog]最长子串

作者:互联网

最长子串

传送门

让\(0\leftarrow -1\),\(1\leftarrow k\),做一次前缀和,原题转化成求最远的两个点,使他们的差为\(0\)。排序一边即可。

code:

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

long long n, k, ans = -2147483647;

struct data{
	long long num, pos;
}s[1000005];
bool cmp(data a, data b) {
	return a.num < b.num;
}
int main() {
	cin >> n >> k;
	for(int i = 1; i <= n; i++) {
		char ch = getchar();
		if(ch == '1') s[i].num = k;
		else s[i].num = -1;
	}
	for(int i = 1; i <= n; i++) {
		s[i].num += s[i - 1].num;
		s[i].pos = i;
	}
	sort(s + 1, s + n + 1, cmp);
	s[0].num = -2147483647;
	long long maxx = -2147483647, minn = 2147483647;
	for(int i = 1; i <= n; i++) {
		if(s[i].num != s[i - 1].num) 
			maxx = s[i].pos,minn=s[i].pos,ans=max(ans,maxx-minn);
		maxx = max(maxx, s[i].pos);
		minn = min(minn, s[i].pos);
		ans = max(ans, maxx - minn);
	}
	cout << ans << endl;
}

标签:子串,leftarrow,int,long,num,tdog,data,最长
来源: https://www.cnblogs.com/yangzq/p/16210011.html