尺取法
大佬的总结
luogu尺取法例题+解析
csdn尺取法例题+解析
1. POJ3061 - Subsequence
题意: 给定一个 N N N 个数的序列,找出最短的连续子序列,使其和大于等于 S S S ,输出最短的子序列长度。
Code:
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
const int INF = 0x3f3f3f3f;
ll a[maxn];
int main()
{
int T;
cin >> T;
while (T--)
{
int n;
ll s;
cin >> n >> s;
for (int i = 0; i < n; i++)
cin >> a[i];
ll sum = 0;
int ans = INF, l = 0, r = 0; //[l,r)
while (true)
{
while (r < n && sum < s)
sum += a[r++];
if (sum < s)
break;
ans = min(ans, r - l);
sum -= a[l++];
}
if (ans == INF)
cout << 0 << endl;
else
cout << ans << endl;
}
return 0;
}
2020.5.16
#include <iostream>
using namespace std;
int a[100005];
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int T, N, S;
cin >> T;
while (T--)
{
cin >> N >> S;
for (int i = 1; i <= N; i++)
cin >> a[i];
int i = 1, j = 0, sum = 0, ans = 1e9;
while (j <= N)
{
if (sum >= S)
{
ans = min(ans, j - i + 1);
sum -= a[i];
i++;
}
else
{
j++;
sum += a[j];
}
}
cout << (ans == 1e9 ? 0 : ans) << endl;
}
return 0;
}