UVa 11093 Just Finish it up 模拟

描述

环形跑道上有n个加油站,第i个加油站可提供量为pi的汽油,从第i个加油站到下一个加油站需要qi量的汽油。选择任意起点,初始油量为0,但可以立刻加油,问能否完成一圈?若能输出字典序最小的站序号,不能则输出无解。

Sample

Input

2
5
1 1 1 1 1
1 1 2 1 1
7
1 1 1 10 1 1 1
2 2 2 2 2 2 2

Output

Case 1: Not possible
Case 2: Possible from station 4

分析

首先可以记录状态,暴力是可以做的。
然后考虑一些情况:(环中)

  • 若从st能到st+n站,但不能到st+n+1站,则从st到st+n都是无解的,因为即是加了st站的汽油都不能走完;
  • 用bool数组判重,若用以上方法,时间复杂度为O(n)。

Code

#include<cstdio>
#include<cstring>

int n, p[100010], q[100010];
bool vis[100010];

int solve()
{   int st = 0, cur = 0;
    int petrol;
    for(; st<n; st++)
    {   if(vis[st]) break;
        vis[st] = 1;
        cur = st;
        //printf("st = %d\n", st);
        petrol = 0;
        while(1)
        {   //printf("cur = %d\n", cur);
            petrol+=p[cur];
            if(petrol>=q[cur])
            {   petrol-=q[cur];
                cur=(cur+1)%n;
                if(cur == st) {return st+1; break;}
            }
            else{st = cur; break;}
        }
    }
    return -1;
}

int main()
{   int t, kas = 0;
    scanf("%d", &t);
    while(t--)
    {   scanf("%d", &n);
        memset(p, 0, sizeof(p));
        memset(q, 0, sizeof(q));
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i<n; i++) scanf("%d",&p[i]);
        for(int i = 0; i<n; i++) scanf("%d",&q[i]);
        int temp = solve();
        if(temp == -1) printf("Case %d: Not possible\n", ++kas);
        else printf("Case %d: Possible from station %d\n",++kas, temp);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值