9276: Candles
时间限制: 1 Sec 内存限制: 128 MB
提交: 70 解决: 34
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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.
来源/分类
题意很好理解,就是在数轴上的n个点选出k个,计算出最小距离
写的时候想了很多奇奇怪怪的想法,但都不太在点上
网上搜题解看到一个很朴素的做法
只有1e5的点,循环一遍也不会t,那么就从最左边的点开始每k个计算一次距离,求出最小的即可
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long ll;
ll a[maxn];
ll ans=1e18;
int main() {
int n,k;
scanf("%d%d",&n,&k);
for(int i=1; i<=n; i++)
cin>>a[i];
int l;
int r;
for(int i=1; i+k-1<=n; i++){
l=i,r=i+k-1;
ans=min(ans,a[r]-a[l]+min(abs(a[l]),abs(a[r])));
}
cout<<ans<<endl;
return 0;
}