Candles(类似滑动窗口)

问题 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;
}
/**/

 

全部评论

相关推荐

10-14 23:01
已编辑
中国地质大学(武汉) Java
CUG芝士圈:虽然是网上的项目,但最好还是包装一下,然后现在大部分公司都在忙校招,十月底、十一月初会好找一些。最后,boss才沟通100家,别焦虑,我去年暑假找第一段实习的时候沟通了500➕才有面试,校友加油
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务