1.链接
登录—专业IT笔试面试备考平台_牛客网
2.题目
3.代码
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e7 + 5;
int n,x;
vector<int> v(N);
int main()
{
cin >> n >> x;
for(int i = 0; i < n;i++) cin >> v[i];
int r,l,sum,len,rr,rl;
r = l = sum = 0;
len = n;
while(r < n)
{
sum += v[r];
while(sum >= x)
{
if(len > r - l)
{
rr = r;
rl = l;
len = r - l;
}
sum -= v[l++];
}
r++;
}
cout << rl+1 << " " << rr+1;
return 0;
}
4.失败代码(博主复习专用,可不看)
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,x;
cin >> n >> x;
vector<int> v(n);
int r,l,rr,rl,count,sum,lens;
r = l = sum = count = 0;
lens = n;
for(int i = 0; i < n; i++)
{
cin >> v[i];
}
for(int i = 0; i < n; i++)
{
if(sum < x)
{
if( i == 0) sum = v[i];
else sum += v[l];
l++;
}
else
{
if(lens >= (l-r) )
{
rl = l;
rr = r;
}
lens = l - r;
r++;
if( sum - v[count] <= x) break;
sum -= v[count];
count++;
}
}
cout << rr + 1 << " "<< rl;
return 0;
}