zoukankan      html  css  js  c++  java
  • 加油站绕圈-数组倍长

    在一个环上有n个加油站,已知第i个加油站可以提供ai的油量,从第i个加油站到第i+1个加油站需要消耗bi的油量。(当i为n时,则表示n到1的油量)

    问:是否能从某个加油站出发,绕环一圈回到这个加油站?(当途中到达某个加油站时的油量小于0则不可)。

     

        public static void main(String[] args) {
            int[] gas = {4,2, 3, 1};
            int[] cost = {1,3, 1, 2};
            System.out.println(canCompleteCircuit2(gas, cost));
        }
    
        /**
         * @param gas=[4,2,3,1]
         * @param cost=[1,3,1,2]
         * @return
         */
        public static int canCompleteCircuit2(int[] gas, int[] cost) {
            int[] gasDouble = new int[gas.length * 2];
            for (int i = 0; i < gasDouble.length; i++) {
                if (i < gas.length) {
                    gasDouble[i] = gas[i];
                } else {
                    gasDouble[i] = gas[i - gas.length];
                }
            }
            int[] costDouble = new int[cost.length * 2];
            for (int i = 0; i < costDouble.length; i++) {
                if (i < cost.length) {
                    costDouble[i] = cost[i];
                } else {
                    costDouble[i] = cost[i - cost.length];
                }
            }
            for (int i = 0; i < gasDouble.length; i++) {
                boolean flag = true;
                int left = 0;
                for (int j = i; j < i + gas.length; j++) {
                    left += gasDouble[j];
                    if (left < costDouble[i]) {
                        flag = false;
                        break;
                    }
                    left -= costDouble[i];
                }
                if (flag) {
                    return i;
                }
            }
            return -1;
        }

    算法参考:https://www.cnblogs.com/andyqsmart/p/5460020.html

  • 相关阅读:
    BZOJ3036: 绿豆蛙的归宿
    BZOJ1419: Red is good
    BZOJ1013: [JSOI2008]球形空间产生器sphere
    BZOJ1415: [Noi2005]聪聪和可可
    BZOJ1417: Pku3156 Interconnect
    BZOJ1076: [SCOI2008]奖励关
    BZOJ2318: Spoj4060 game with probability Problem
    BZOJ1426: 收集邮票
    BZOJ2720: [Violet 5]列队春游
    BZOJ2698染色
  • 原文地址:https://www.cnblogs.com/use-D/p/13374417.html
Copyright © 2011-2022 走看看