zoukankan      html  css  js  c++  java
  • Codeforces Round #436 C. Bus

    题意:一辆车在一条路上行驶,给你路的总长度a,油箱的容量b,加油站在距离起点的距离f,以及需要走多少遍这条路k(注意:不是往返)

         问你最少加多少次油能走完。

    Examples
    Input
    6 9 2 4
    Output
    4
    Input
    6 10 2 4
    Output
    2
    Input
    6 5 4 3
    Output
    -1

    思路:把需要走的路程拉直来看,那么相邻两次经过加油站之间的路程为2*f或2*(a-f),再加上一些特判就好了。

    代码:
    #include<iostream>
    #include<string.h>
    using namespace std;

    long long a,b,f,k;

    int main(){
        cin>>a>>b>>f>>k;
        if(k==1){   //特判只要走一遍时的情况
            if(b>=a)cout<<0<<endl;
            else {
                if(b>=f&&b>=a-f)cout<<1<<endl;
                else cout<<-1<<endl;
            }
            return 0;
        }
        long long x=2*f,y=2*(a-f),sum=f,last=b-f,c=0;
        //x和y记录的是在两次经过加油站之间的路程的两种情况
        //sum记录的是已经走过了多少路程,从第一次经过加油站开始算
        //last记录的是油箱中所剩的油
        //c记录加油次数
        bool flag=1;
        int op=2;
        if(last<0){  //连加油站都走不到
            cout<<-1<<endl;
            return 0;
        }
        while(1){
            if(k*a-sum==f||k*a-sum==a-f){//在最后一次经过加油站时需要特判
                int w;
                if(k*a-sum==f)w=f;
                else w=a-f;
                if(last<w)c++;
                break;
            }
            if(op==1){   //op=1表示x这种情况
                if(last<x){
                    last=b-x;
                    c++;
                }
                else last-=x;
                sum+=x;
                op=2;
            }
            else {     //op=2表示y这种情况
                if(last<y){
                    last=b-y;
                    c++;
                }
                else last-=y;
                sum+=y;
                op=1;
            }
            if(last<0){//如果中间出现了油箱为负的情况,那么表示走不到
                flag=0;
                break;
            }
        }
        if(flag==0)cout<<-1<<endl;
        else cout<<c<<endl;
        return 0;
    }

  • 相关阅读:
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA
    leetcode刷题笔记 222题 完全二叉树的节点个数
    leetcode刷题笔记 221题 最大正方形
    leetcode刷题笔记 220题 存在重复元素 III
    leetcode刷题笔记 219题 存在重复元素 II
    leetcode刷题笔记 218题 天际线问题
    leetcode刷题笔记 216题 组合总和 III
  • 原文地址:https://www.cnblogs.com/ljy08163268/p/7634723.html
Copyright © 2011-2022 走看看