题目描述
There are N candles placed on a number line. The i-th candle from the left is placed on coordinate xi. Here, x1<x2<…<xN holds.
Initially, no candles are burning. Snuke decides to light K of the N candles.
Now, he is at coordinate 0. He can move left and right along the line with speed 1. He can also light a candle when he is at the same position as the candle, in negligible time.
Find the minimum time required to light K candles.
Constraints
·1≤N≤105
·1≤K≤N
·xi is an integer.
·|xi|≤108
·x1<x2<…<xN
输入Input is given from Standard Input in the following format:
N K
x1 x2 … xN
输出Print the minimum time required to light K candles.
样例输入
5 3
-30 -10 10 20 50
样例输出
40
提示:
He should move and light candles as follows:
·Move from coordinate 0 to −10.
·Light the second candle from the left.
·Move from coordinate −10 to 10.
·Light the third candle from the left.
·Move from coordinate 10 to 20.
·Light the fourth candle from the left.
//大概需要一点贪心吧,然后学习用一下0x3f3f3f3f,
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string.h>
#include <math.h>
#include <map>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
ll a[1000000];
int main()
{
ll n,k,i,j;
ll ans=inf;
scanf("%lld%lld",&n,&k);
for(i=1; i<=n; i++)
scanf("%lld",&a[i]);
for(i=1; i+k-1<=n; i++)
{
int l=i,r=i+k-1;
ans=min(ans,a[r]-a[l]+min(abs(a[l]),abs(a[r])));
/*我们可以从最大的数开始,逐渐取最小值,主要是这个过程不太好懂,r=i+k-1,因为正好
和l相隔k个点(加上他们自己),我们一组一组的找最小值,a[r]-a[l]是相隔的距离,abs就是找的绝对值,
代表最小的距离,就要先去哪一个点。如果实在不好理解,你可以把每个ans输出出来看一下,
应该就好理解了,嘻~*/
}
printf("%lld",ans);
return 0;
}
我就是个小白,也是参考了下面的文章才搞懂的,嘻~。
https://blog.csdn.net/renzijing/article/details/84887922