题目描述:
Mary and Rose own a collection of jewells. They want to split the collection among themselves so that both receive an equal share of the jewels. This would be easy if all the jewels had the same value, because then they could just split the collection in half. But unfortunately, some of the jewels are larger, or more beautiful than others. So, Mary and Rose start by assigning a value, a natural number between one and ten, to each jewel. Now they want to divide the jewels so that each of them gets the same total value. Unfortunately, they realize that it might be impossible to divide the jewels in this way (even if the total value of all jewels is even). For example, if there are one jewel of value 1, one of value 3 and two of value 4, then they cannot be split into sets of equal value. So, they ask you to write a program that checks whether there is a fair partition of the jewels.
输入描述:
<span style="color:#000000">Each line in the input file describes one collection of jewels to be divided. The lines contain ten non-negative integers n1 , . . . , n10 , where ni is the number of jewels of value i. The maximum total number of jewells will be 10000.
The last line of the input file will be "0 0 0 0 0 0 0 0 0 0"; do not process this line.
</span>
输出描述:
<span style="color:#000000">For each collection, output "#k:", where k is the number of the test case, and then either "Can be divided." or "Can't be divided.".
Output a blank line after each test case.
</span>
样例输入:
复制
1 0 1 2 0 0 0 0 2 0
1 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
样例输出:
#1:Can't be divided.
#2:Can be divided.
题意很明白,就是能不能将宝石分为两堆,且两堆价值一样,所以总价值应该是偶数,
如果总价为偶数,那么剩下的就是动态规划,如果book[sum1/2]=1则表示能成功,否则为失败
注意每行输出后面换行后还要加一个空行,我被这个空行坑了五六次
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<set>
using namespace std;
int a[11],b[100005],h,sum1,book[500005],t=0;
int main()
{
while(1){
fill(book,book+500005,0); //标记数组,标记是否能组成
fill(b,b+100005,0); //用来盛放所有宝石
sum1=0; //总价值
h=0; //宝石个数
t++; //测试次数
for(int i=1;i<11;i++){
cin>>a[i];
sum1+=a[i]*i;
int num=a[i];
while(num--){
b[h++]=i; //将a[i]个价值为i的宝石放入b数组中
}
}
if(!sum1)break; //若总价值为0,退出
if(sum1%2!=0){ //若总价值不为偶数则肯定不会成功
printf("#%d:Can't be divided.\n\n",t);
continue;
}
book[0]=1;
for(int j=0;j<h;j++){ //动态规划
for(int i=sum1/2;i>=b[j];i--){
if(book[i-b[j]])book[i]=1;
}
}
if(book[sum1/2])printf("#%d:Can be divided.\n\n",t); //判断总价值/2能不能组成
else printf("#%d:Can't be divided.\n\n",t);
}
return 0;
}