Codeforces Beta Round 6 C - Alice, Bob and Chocolate
地址:
https://codeforces.com/contest/6
以上地址,可以打开,在国内,可以注册,可以在上面做题。我已经做了11天的题了。
速度可以,没有感觉到慢。
题意:
Alice从左边吃巧克力,Bob从右边吃,如果都一样的时间,Bob会让Alice先吃。
每个数字代表一个巧克力,而数字代表吃掉巧克力消耗的时间,当两个人消耗时间一样,就Alice先吃,但是一个巧克力不能分2不分吃。他们吃的速度一样,所以这里只要考虑时间之和sum就可以了。
注意:这里就需要,从左边开始判断,如果Alice time <=Bob time,那么优先Alice,即left左边
程序的思路:
1)首先左右各开始吃0,n-1,2)然后当使用时间少的吃下一个1,n-1-1,此时时间耗时多的还在吃。
3)当时间一样,就先左边吃。所以这里判段条件一定要先left
理解题意:例如2 9 8 2 7 表示5各巧克力,数字代表吃完所需时间。
比如Alice吃了第一个,消耗时间是2分钟,Bob吃了右边第一个,消耗时间是7分钟,接下来,Alice不可能等Bob吃完再吃,所以会用时少的马上吃下一个
这里的判定条件就是left time<=right time, 直到索引位置用完。(当相同时间,先左边吃)
有那么一丢丢别扭,做多了这样的题,就有经验了。此题也是参考别人写的,我自己写的遇到测试数据10万的时候就出错。(推测:主要没有体现先左边后右边思路。不过参考这个代码写的更严谨。)(一个开发人员,不光要学会for,最重要也要灵活用while,)
写代码最重要的是不断学习新的思路方法,这样才能拓展自己的逻辑思维,形成肌肉记忆!长久保存在大脑细胞神经里。
遇到此类左右同时进行消耗的题,就用这种方法。
以下是代码
#include <iostream>
#include <vector>
using namespace std;int main()
{int n = 0, v1 = 0;cin >> n;if (n <= 0){return 0;}vector<int> list;for (int i = 0; i < n; i++){cin >> v1;list.push_back(v1);}// index=0 is already get!int left_index = 1;//while is from 1int right_index = n - 1 - 1; //while is from n-1-1int left_sum = 0, right_sum = 0;int left_cout = 0, right_cout = 0;//start from index=0left_sum += list[0];left_cout++;if (list.size() == 1){cout << "1 0" << endl;return 0;}right_sum += list[n - 1];right_cout++;while (left_index <= right_index){// when is ==, so left++if (left_sum <= right_sum){ // who min,who ++left_sum += list[left_index];left_cout++;left_index++;}else{right_sum += list[right_index];right_cout++;right_index--;}}cout << left_cout << " " << right_cout << endl;return 0;
}/*
https://codeforces.com/contest/6/problem/C
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(n>=1)
— the amount of bars on the table.The second line contains a sequence t1,t2...tn(t1>0),
where ti is the time (in seconds) needed to consume the i-th bar
(in the order from left to right).Examples
InputCopy
5
2 9 8 2 7
OutputCopy
2 3Input
1
1
Output
1 1
Answer
1 0
Checker Log
wrong answer 2nd numbers differ - expected: '0', found: '1'*/