贴下原题:
Dividing
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions:74237 | Accepted: 19419 |
Description
Marsha and Bill own a collection of marbles. They want to split the collection among themselves so that both receive an equal share of the marbles. This would be easy if all the marbles had the same value, because then they could just split the collection in half. But unfortunately, some of the marbles are larger, or more beautiful than others. So, Marsha and Bill start by assigning a value, a natural number between one and six, to each marble. Now they want to divide the marbles so that each of them gets the same total value. Unfortunately, they realize that it might be impossible to divide the marbles in this way (even if the total value of all marbles is even). For example, if there are one marble 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 marbles.
Input
Each line in the input file describes one collection of marbles to be divided. The lines contain six non-negative integers n1 , . . . , n6 , where ni is the number of marbles of value i. So, the example from above would be described by the input-line "1 0 1 2 0 0". The maximum total number of marbles will be 20000.
The last line of the input file will be "0 0 0 0 0 0"; do not process this line.
The last line of the input file will be "0 0 0 0 0 0"; do not process this line.
Output
For each collection, output "Collection #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.
Output a blank line after each test case.
Sample Input
1 0 1 2 0 0 1 0 0 0 1 1 0 0 0 0 0 0
Sample Output
Collection #1: Can't be divided. Collection #2: Can be divided.
题意就是说:有一堆大理石,质量有1,2,3,4,5,6六种,大理石不可以分割,要求你输入大理石各种质量的数量,然后判断他们能不能分成两组。。
当然。。作为一个当开始学习的小白,什么多重背包啥的我也不懂,不过我觉得用搜索就可以做出来。。
代码如下:
#include<iostream>
using namespace std;
int a[7];
int totalvalue;
int halfvalue;
bool flag;
int temp;
void DFS(int value,int index)
{
if(flag)
return;
if(value==halfvalue)
{
flag=true;
return;
}
for(int i=index;i>=1;i--)
{
if(a[i]!=0)
{
if(value+i<=halfvalue)
{
a[i]--;
DFS(value+i,i);
if(flag)
break;
}
}
}
return;
}
int main(int i)
{
int t=1;
while(cin>>a[1]>>a[2]>>a[3]>>a[4]>>a[5]>>a[6])
{
if(a[1]+a[2]+a[3]+a[4]+a[5]+a[6]==0)
break;
totalvalue=a[1]*1+a[2]*2+a[3]*3+a[4]*4+a[5]*5+a[6]*6;
if(totalvalue%2!=0)
{
temp=0;
}
else
{
halfvalue=totalvalue/2;
flag=false;
DFS(0,6);
if(flag)
temp=1;
else
temp=0;
}
if(temp==0)
{
cout<<"Collection #"<<t<<':'<<endl;
cout<<"Can't be divided."<<endl<<endl;
}
else
{
cout<<"Collection #"<<t<<':'<<endl;
cout<<"Can be divided."<<endl<<endl;
}
t+=1;
}
return 0;
}