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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章