博客
关于我
加油站(贪心)
阅读量: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/

    你可能感兴趣的文章
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>