POJ 1247 Magnificent Meatballs(我的水题之路——数组两边求和)

来源:互联网 发布:钛备份如何恢复数据 编辑:程序博客网 时间:2024/05/16 12:46
Magnificent Meatballs
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 5225 Accepted: 3527

Description

Sam and Ella run a catering service. They like to put on a show when serving meatballs to guests seated at round tables. They march out of the kitchen with pots of meatballs and start serving adjacent guests. Ella goes counterclockwise and Sam goes clockwise, until they both plop down their last meatball, at the same time, again at adjacent guests. This impressive routine can only be accomplished if they can divide the table into two sections, each having the same number of meatballs. You are to write a program to assist them. 

At these catering events, each table seats 2 <= N <= 30 guests. Each guest orders at least one and at most nine meatballs. Each place at the table is numbered from 1 to N, with the host at position 1 and the host's spouse at position N. Sam always serves the host first then proceeds to serve guests in increasing order. Ella serves the spouse first, then serves guests in decreasing order. The figures illustrate the first two example input cases. 

Input

Input consists of one or more test cases. Each test case contains the number of guests N followed by meatballs ordered by each guest, from guest 1 to guest N. The end of the input is a line with a single zero. 

Output

For each table, output a single line with the ending positions for Sam and Ella, or the sentence indicating an equal partitioning isn't possible. Use the exact formatting shown below. 

Sample Input

5 9 4 2 8 35 3 9 4 2 86 1 2 1 2 1 26 1 2 1 2 1 10

Sample Output

Sam stops at position 2 and Ella stops at position 3.No equal partitioning.No equal partitioning.Sam stops at position 3 and Ella stops at position 4.

Source

Mid-Central USA 2002

这道题要求是一个分肉丸的问题,每次会来N个客人,每个客人要求的肉丸数量不一,有两个仆人,分别从第一个客人和最后一个客人出发,分别逆时针、顺时针移动,两个人分肉丸的速度相同,即,分一个肉丸给客人的所消耗的时间相同,问,是否他们两个人会在某一两个相邻位置相遇,且同时分完所在人的肉丸。

解法是,用一个数组记录所有人的要肉丸的个数,且同时记录下肉丸总数,用一个下标变量,从0开始,将数组分为两边,求下标每向后移动一个人之后,两边的肉丸数量是否相同,如果相同则存在这样的位置,如果一直没有则不存在。

代码(1AC O(∩_∩)O!):
#include <cstdio>#include <cstdlib>#include <cstring>int N;int need[50];int main(void){    int i;    int left, right, sum;    int flag = 0;    while (scanf("%d", &N), N != 0){        flag = 0;        memset(need, 0, sizeof(need));        for (i = sum = 0; i < N; i++){            scanf("%d", &need[i]);            sum += need[i];        }        for (i = left = 0, right = sum; right >= left; i++){            left += need[i];            right -= need[i];            if (left == right){                i++;                printf("Sam stops at position %d and Ella stops at position %d.\n", i, i + 1);                flag = 1;                break;            }        }        if (flag == 0){            printf("No equal partitioning.\n");        }    }    return 0;}


原创粉丝点击