Candles(類似滑動視窗)
阿新 • • 發佈:2018-11-26
問題 C: Candles
時間限制: 1 Sec 記憶體限制: 128 MB
題目描述
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.
/**/ #include <cstdio> #include <cstring> #include <cmath> #include <cctype> #include <iostream> #include <algorithm> #include <map> #include <set> #include <vector> #include <string> #include <stack> #include <queue> typedef long long LL; using namespace std; int n, k; int a[100005]; int min(int x, int y){ return x < y ? x : y; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); scanf("%d %d", &n, &k); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); //if(a[i] < 0) a[i] = a[i] * 2; } int ans = 0x3f3f3f3f; for (int i = k; i <= n; i++){ ans = min(ans, a[i] - a[i - k + 1] + min(abs(a[i]), abs(a[i - k + 1]))); } printf("%d\n", ans); return 0; } /**/