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

    你可能感兴趣的文章
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>