现在的位置: 首页 > 综合 > 正文

poj 1014 & zoj 1149 Dividing(多重背包+倍增思想优化)

2012年12月26日 ⁄ 综合 ⁄ 共 2182字 ⁄ 字号 评论关闭

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

题目Poj:http://poj.org/problem?id=1014 Zoj:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1149

分析:这题算是多重背包+倍增思想优化挺好的入门题,首先要想到用多重背包来做这题,然后就是优化部分了,因为数据还是挺大的,不优化恐怕会超时吧,然后就是倍增思想了,也就是利用二进制的一些特性,具体的讲解还是看看背包九讲吧。。。

代码:

#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:\n",++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;
}

抱歉!评论已关闭.