C. ALICE, BOB AND CHOCOLATE

http://www.yyycode.cn/index.php/2020/05/20/c-alice-bob-and-chocolate/


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.

How many bars each of the players will consume?Input

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t 1, t 2, …, t n (1 ≤ t i ≤ 1000), where t i is the time (in seconds) needed to consume the i-th bar (in the order from left to right).Output

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.ExamplesinputCopy

5
2 9 8 2 7

outputCopy

2 3

题意:放在桌上一层巧克力,女的从左边开吃,男的从右边开吃,每一个巧克力都有吃的时间,如果两个人吃到同一块,女士优先。问男女各吃了多少个巧克力。

思路:题目是双指针模拟不难,但是卡边界很难受。要注意,如果n=1,特判,然后for里面i<=j,在if里面先特判i+1==j的时候ans++,break;

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
typedef long long LL;
LL a[maxn];
LL suml[maxn];
LL sumr[maxn];
int main(void)
{
    LL n;cin>>n;
    for(LL i=1;i<=n;i++) cin>>a[i];
    for(LL i=1;i<=n;i++) suml[i]=suml[i-1]+a[i];
    for(LL i=n;i>=1;i--) sumr[i]=sumr[i+1]+a[i];
    if(n==1) {cout<<1<<' '<<0<<endl;}
    else 
    {
        LL ans1=1;LL ans2=1;
        LL i=1;LL j=n;
        for( i=1,j=n;i<=j;)
        {
            if(suml[i]<=sumr[j])
            {
                 if(i+1==j) {break;}
                 ans1++;i++;
                 
            }
            if(suml[i]>sumr[j])
            {
             if(j-1==i){break;}
             ans2++;j--;
             
            }
        }
        cout<<ans1<<' '<<ans2<<endl;
    }    
  
    
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/106244109