问题 P: Candles

题目描述
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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值