博客
关于我
加油站(贪心)
阅读量:368 次
发布时间:2019-03-04

本文共 1509 字,大约阅读时间需要 5 分钟。

为了解决这个问题,我们需要找到一个加油站作为起点,使得从该起点出发,车辆可以沿着环形路线完成一圈而不中途停车。我们需要计算整个环路的总油量变化,并确保在每个阶段油量变化不为负,同时总油量变化足够。

方法思路

  • 计算总油量变化:首先,我们计算整个环路的总油量变化 sum_total。如果 sum_total 小于零,显然无法完成环路,直接返回 -1。
  • 遍历每个加油站作为起点:对于每个加油站,我们假设它是起点,计算从该点出发到下一个加油站的油量变化。如果在任何一步油量变化为负,则该起点不合适。
  • 检查整个环路:如果从某个起点出发,整个环路的油量变化等于 sum_total 且在每个阶段油量变化不为负,则该起点是答案。
  • 解决代码

    #include 
    using namespace std;int canCompleteCircuit(vector
    & gas, vector
    & cost) { int n = gas.size(); int sum_total = 0; for (int i = 0; i < n; ++i) { sum_total += gas[i] - cost[i]; } if (sum_total < 0) { return -1; } for (int i = 0; i < n; ++i) { int current = 0; bool canComplete = true; for (int j = i; j < n; ++j) { current += gas[j] - cost[j]; if (current < 0) { canComplete = false; break; } } if (!canComplete) { continue; } for (int j = 0; j < i; ++j) { current += gas[j] - cost[j]; if (current < 0) { canComplete = false; break; } } if (canComplete && current == sum_total) { return i; } } return -1;}

    代码解释

  • 计算总油量变化:首先,我们遍历所有加油站,计算每个加油站的油量变化,并累加得到 sum_total
  • 检查总油量变化:如果 sum_total 小于零,直接返回 -1。
  • 遍历每个起点:对于每个加油站,作为起点,计算从该点出发到下一个加油站的油量变化。如果在任何一步油量变化为负,则跳过该起点。
  • 检查整个环路:如果从某个起点出发,整个环路的油量变化等于 sum_total,则返回该起点的下标。
  • 返回结果:如果遍历完所有起点都没有找到合适的,返回 -1。
  • 这种方法确保了我们能够在每个阶段检查油量变化,并且在整个环路中确保总油量变化满足要求,从而找到正确的起点。

    转载地址:http://ufdg.baihongyu.com/

    你可能感兴趣的文章
    NOIP2011T1 数字反转
    查看>>
    NOIP2014 提高组 Day2——寻找道路
    查看>>
    NOIp模拟赛二十九
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>