zoukankan      html  css  js  c++  java
  • UVa 11093

    链接:

    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2034

    题意:

    环形跑道上有n(n≤100000)个加油站,编号为1~n。第i个加油站可以加油pi加仑。从加油站i开到下一站需要qi加仑汽油。
    你可以选择一个加油站作为起点,初始油箱为空(但可以立即加油)。你的任务是选择一个起点,使得可以走完一圈后回到起点。
    假定油箱中的油量没有上限。如果无解,输出Not possible,否则输出可以作为起点的最小加油站编号。

    分析:

    考虑1号加油站,直接模拟判断它是否为解。如果是,直接输出;
    如果不是,说明在模拟的过程中遇到了某个加油站p,在从它开到加油站p+1时油没了。
    这样,以2, 3,…, p为起点也一定不是解(想一想,为什么)。这样,使用简单的枚举法便解决了问题,时间复杂度为O(n)。

    代码:

     1 #include <cstdio>
     2 
     3 int n, a[100000+5];
     4 
     5 int solve(){
     6     int oil = 0, amount = 0;
     7     for(int start = 0; start < n; start++){
     8         for(int cur = start; ; cur = (cur + 1) % n){
     9             if(cur == start){
    10                 if(++amount == 2) return start + 1;
    11             }
    12             oil += a[cur];
    13             if(oil < 0){
    14                 if(cur < start) return 0;
    15                 start = cur;
    16                 oil = amount = 0;
    17                 break;
    18             }
    19         }
    20     }
    21     return 0;
    22 }
    23 
    24 int main(){
    25     int T;
    26     scanf("%d", &T);
    27     for(int cases = 1; cases <= T; cases++){
    28         scanf("%d", &n);
    29         for(int i = 0; i < n; i++) scanf("%d", &a[i]);
    30         for(int need, i = 0; i < n; i++){
    31             scanf("%d", &need);
    32             a[i] -= need;
    33         }
    34         int station = solve();
    35         if(!station) printf("Case %d: Not possible
    ", cases);
    36         else printf("Case %d: Possible from station %d
    ", cases, station);
    37     }
    38     return 0;
    39 }
  • 相关阅读:
    check事件
    JAVA----泛型
    JAVA集合的遍历for循环、Iterator迭代器
    JAVA 集合的定义分类
    JAVA面向对象---方法的重写与重载
    JAVA 面向对象---继承
    JAVA 面向对象
    JAVA ArrayList集合
    JAVA基础测试
    JAVA中 引用数据类型(类)
  • 原文地址:https://www.cnblogs.com/hkxy125/p/8140385.html
Copyright © 2011-2022 走看看