尺取法(滑动窗口法)

丢手绢
code:

#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e5 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
ll n, m;
int a[maxn], res = 0, sum;
void work()
{
	cin >> n;
	for(int i = 1; i <= n; ++i) cin >> a[i], sum += a[i];
	int l = 1, r = 1, ans = 0;
	while(l <= n)
	{
	//一个点离其他点的最远距离一定是在总距离的一半的两边
		while(res < sum / 2){
			if(r > n) r = 1;
			res += a[r];
			++r;
		}
		ans = max(ans, min(res, sum - res));
		res -= a[l];
		++l;
	}
	cout << ans;
}

int main()
{
	ios::sync_with_stdio(0);
//	int TT;cin>>TT;while(TT--)
	work();
	return 0;
}

字符串

#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e5 + 9;
const int mod = 1e9 + 7;
ll n, m;
int a[30], cnt = 0;
void work()
{
	string s;cin >> s;
	n = s.size();
	int l = 0, r = 0, ans = 1e6;
	while(l < n)
	{
		while(cnt < 26 && r < n){// 先找到一个从l开始满足条件的子串
			int x = s[r] - 'a';
			if(!a[x]) ++cnt;
			a[x]++;
			++r;
		}
		if(cnt == 26) ans = min(ans, r - l);// 只要满足条件就更新
		a[s[l] - 'a']--;// 左指针右移,删去不包含的
		if(!a[s[l]-'a']) --cnt;
		++l;// 右移试图缩小满足条件的子串长度
	}
	cout << ans;
}

int main()
{
	ios::sync_with_stdio(0);
//	int TT;cin>>TT;while(TT--)
	work();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值