poj1014 & zoj1149 Dividing(다중 가방 + 배증 사상 최적화)

Dividing
Time Limit: 1000MS
 
Memory Limit: 10000K
Total Submissions: 40539
 
Accepted: 10061
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.
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.
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.
Source
Mid-Central European Regional Contest 1999
제목 Poj:http://poj.org/problem?id=1014 Zoj: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1149
분석: 이 문제는 다중 배낭+배증 사상 최적화가 좋은 입문 문제라고 할 수 있다. 우선 다중 배낭으로 이 문제를 풀고 그 다음에 최적화 부분을 생각해야 한다. 데이터가 매우 크기 때문에 최적화하지 않으면 시간을 초과할 수 있다. 그 다음에 배증 사상이다. 즉, 2진법의 일부 특성을 이용하여 구체적인 설명은 배낭 9강을 살펴보자.
코드:
#include<cstdio>
using namespace std;
int a[7],sum;
bool f[66666];
void ZeroOnePack(int v)
{
    for(int i=sum;i>=v;--i)f[i]|=f[i-v];
}
int main()
{
    int i,k,t=0;
    while(1)
    {
        for(sum=0,i=1;i<7;++i)scanf("%d",&a[i]),sum+=a[i]*i;
        if(!sum)break;
        printf("Collection #%d:
",++t); if(sum&1) { puts("Can't be divided."); puts(""); continue; } for(sum>>=1,i=f[0]=1;i<=sum;++i)f[i]=0; for(i=1;i<7;++i) if(a[i]) { k=1; while(k<a[i]) { ZeroOnePack(k*i); a[i]-=k; k<<=1; } ZeroOnePack(a[i]*i); } if(f[sum])puts("Can be divided."); else puts("Can't be divided."); puts(""); } return 0; }

좋은 웹페이지 즐겨찾기