Divide
Description
Alice and Bob has found a island of treasure in byteland! They find N kinds of treasures on the island, and each kind of treasure has a certain number, and as in byteland, the value of each treasure will be a power of 2, such as 1,2,4,8 ...
Now the only problem is how to divide treasures fairly, they need to divide the treasures into two parts, and the value of each part is the sum of all treasures' in this part, they want to make the difference between the value of two parts as small as possible, can you help them?
Input
First line of the input is a single integer T(1 <= T <= 20), indicating there are T test cases.
For each test case, the first line contain one integer N(2 <= N <= 10^5), indicate the different kinds of treasures.
Then N line followed, each line will have follow two integer ai(0 <= ai <= 10^5) and xi(0 <= xi <= 10^9), indicate there are xi i-th treasures, and the value of each one is 2^ai.
Output
For each case, you should output a single line, first output "Case #t: ", where t indicating the case number between 1 and T, then a string with only '0' and '1' followed, indicate the minimum difference in binary representation, find more details in samples.
Sample Input
3
2
0 2
2 1
4
0 1
1 1
2 1
3 1
4
0 2
1 1
2 1
3 1
Sample Output
Case #1: 10
Case #2: 1
Case #3: 0
Source
Sichuan State Programming Contest 2012
题目大意:给你N种价值的物品,物品有两个属性,一个是数量,一个是价值(价值是以2的ai次方表示的)。为了公平起见,求出宝藏分配的最小差(二进制表示)。
分析:当我们把宝藏合成后,即2*2^(n-1)宝藏=1*2^n宝藏(即二进制的进位处理),如果价值最大的宝藏可一分为二,那么该宝藏不会影响最终的结果(即该部分差值为0),如果价值最大的宝藏不可平分,那么必定结果必定是 该宝藏的价值-剩余宝藏的和 。(当进位处理后,差值最小的情况:2^n-(2^(n-2)+2^(n-2)+…+2^2+2^1)=1)。维护一个模拟二进制数组来记录宝藏的分布,比如a[2]=4表示2的2次方的宝藏有4个;然后进行进位处理,这时候我们需要一个标记数组,为什呢?因为当进位后如果某一位是1,这个1有两种情况:1>、这个1是进位得到的,那么它可以转换为比它低一位的2,比如:a[2]=1(进位的到),a[1]=0;这个时候相当于a[1]=2,即宝藏是可分的,不会影响结果。2>、这个1是本身就有的,那么则意味着该宝藏不可分,也就是找到可以得到答案的最大宝藏。很显然我们需要标记进位过程中哪一位的1是由进位得到的(这个过程很重要)。那么剩下的问题就是二进制的相减:题目中的减法很有特点,一定是1000000…(n个0)减去另一个二进制数,我们可以把这个二进制数转换为111111111…(n个1)+1;下面相减的过程就是一个简单的取反过程。
实现代码如下:
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn=100005;
const int INFF=0x7fffffff;
LL a[maxn];
LL ans[maxn];
bool fg[maxn];
int main()
{
int T,i,Case=1;
scanf("%d",&T);
while(T--)
{
memset(a,0,sizeof a);
memset(fg,false,sizeof fg);
memset(ans,0,sizeof ans);
int n,val,num,max=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&val,&num);
if(max<val)
max=val; //纪录宝藏最大价值的二进制编号
a[val]+=num; //累加同一价值的宝藏数目
}
for(i=0;i<=max;i++)
{
if(a[i]>=2)
{
a[i+1]+=a[i]/2;
a[i]%=2;
fg[i+1]=true; //标记进位1
}
}
int id=0;
for(i=max;i>0;i--)
{
if(a[i]%2==1 && !fg[i])
{
id=i; //找到最大的不可平分的宝藏编号
break;
}
}
printf("Case #%d: ",Case++);
if(id==0) //只有价值最小的一个宝藏不可平分
{
printf("%lld\n",a[0]);
continue;
}
ans[0]=1; //我们把不可分的宝藏表示为11111...+1的形式
for(i=id-1;i>=0;i--)
ans[i]+=(1-a[i]%2);
for(i=0;i<=id;i++)
if(ans[i]>=2)
{
ans[i]=0;
ans[i+1]++;
}
for(i=id+1;i>=0;i--)
{//除去前导零
if(ans[i]==1)
break;
}
for(;i>=0;i--)
printf("%lld",ans[i]);
puts("");
}
return 0;
}