首页 > 代码库 > hdu3280Equal Sum Partitions (区间DP)
hdu3280Equal Sum Partitions (区间DP)
Problem 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.
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 integerM, (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题意:给出一个序列,如果能把该序列分成若干段,使每段和相等,求最小和,若不能分则和为这一整序列。#include<stdio.h> int dp[7000][7000]; int min(int a,int b) { return a>b?b:a; } int main() { int a[10005],ans[10005],t,c,m; scanf("%d",&t); while(t--) { scanf("%d%d",&c,&m); ans[0]=0; for(int i=1;i<=m;i++) { scanf("%d",&a[i]); ans[i]=ans[i-1]+a[i]; } for(int r=0;r<m;r++) for(int i=1;i<=m-r;i++) { int j=i+r; dp[i][j]=ans[j]-ans[i-1]; for(int k=i;k<j;k++) { if(ans[k]-ans[i-1]==dp[k+1][j]) dp[i][j]=min(dp[i][j],dp[k+1][j]); if(dp[i][k]==ans[j]-ans[k]) dp[i][j]=min(dp[i][j],dp[i][k]); if(dp[i][k]==dp[k+1][j]) dp[i][j]=min(dp[i][j],dp[i][k]); } } printf("%d %d\n",c,dp[1][m]); } }
hdu3280Equal Sum Partitions (区间DP)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。