Equal Sum Partitions

Equal Sum Partitions

 

Time Limit:   1000MS       Memory Limit:   65535KB
Submissions:   111       Accepted:   45

 

Description

An equal sum partition of a sequence of numbers is a grouping of the numbers (in the same order as the original sequence) in such a way that each group has the same sum.  For example, the sequence:

2 5 1 3 3 7

may be grouped as:

(2 5) (1 3 3) (7)
 
to yield an equal sum of 7.
 
Note: The partition that puts all the numbers in a single group is an equal sum partition with the sum equal to the sum of all the numbers in the sequence.
 
For this problem, you will write a program that takes as input a sequence of positive integers and returns the smallest sum for an equal sum partition of the sequence

 

Input

The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow.  The first line of each data set contains the data set number, followed by a space, followed by a decimal integer M, (1 ≤ M ≤ 10000), giving the total number of integers in the sequence.  The remaining line(s) in the dataset consist of the values, 10 per line, separated by a single space.  The last line in the dataset may contain less than 10 values.

 

Output

For each data set, generate one line of output with the following values:  The data set number as a decimal integer, a space, and the smallest sum for an equal sum partition of the sequence.

 

Sample Input

 

3 
1 6 
2 5 1 3 3 7 
2 6 
1 2 3 4 5 6 
3 20 
1 1 2 1 1 2 1 1 2 1 
1 2 1 1 2 1 1 2 1 1 

 

Sample Output

 

1 7 
2 21 
3 2

解析:
由2 5 1 3 3 7分为(2 5)(1 3 3)(7)可以清晰看出这道题是对这列数进行最小均分,肯定就会用到DFS思想(递归),实现过程看代码吧:
# include<stdio.h>
int sign[10005];
int num,res,leap;
int solve(int sum,int index)
{
    if(index==num&&leap==0)//满足条件
    {
        res=sum;
        return 1;
    }
    else if(index==num)//对应的sum不满足
        return 0;
    leap+=sign[index];//leap为暂时计数器
    if(sum==leap)
    {
        leap=0;
    return solve(sum,index+1);
    }
    else if(sum>leap)
    return solve(sum,index+1);
    else return 0;
}
int main()
{
    int nCase;
    int cnt,sum,i;
    scanf("%d",&nCase);
    while(nCase--)
    {
        scanf("%d %d",&cnt,&num);
        sum=0;
        for(i=0;i<num;i++)
        scanf("%d",&sign[i]);
        for(i=0;i<num;i++)
        {
            sum+=sign[i];
            leap=0;
            if(solve(sum,i+1))break;//如果不满足,sum就会逐渐往后加
        }
        printf("%d %d\n",cnt,res);
    }
    return 0;
}

 

posted on 2013-03-08 18:22  即为将军  阅读(369)  评论(0)    收藏  举报

导航