UESTC 1711 Divide 解题报告

来源:互联网 发布:房地产网络推广软文 编辑:程序博客网 时间:2024/06/06 07:34

Divide

Time Limit: 2000 ms Memory Limit: 65535 kB Solved: 30 Tried: 743

Submit

Status

Best Solution

Back

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


思路:

 用一个数组记录下每个二进制位上的值,满2进位,
从高位到低位扫一遍,找到不能被均分的最高位(当前位为1而且不是进位获得的),
该位置代表的值减去比它低位的值就是答案了

#include <cstdio>#include <cstring>#include <algorithm>#define LL long longconst long M=110000;LL pos[M],JinWei[M],ans[M],max_pos;long n,t;int main(){scanf("%d",&t);for (long l=1;l<=t;++l){scanf("%d",&n);memset(pos,0,sizeof(pos));memset(JinWei,0,sizeof(JinWei));max_pos=0;long max1=0;while (n--){long x,a;scanf("%d%d",&a,&x);pos[a]+=x;max1=std::max(max1,a);//max_pos=std::max(max_pos,a);}for (long i=0;i<M;++i)if (pos[i]>1){pos[i+1]+=(pos[i]>>1);JinWei[i+1]=1;//pos[i]=pos[i]%1;pos[i]=pos[i]%2;}max_pos=-1;for (long i=M-1;i>=0;--i)if (pos[i] && !JinWei[i]){max_pos=i;break;}printf("Case #%d: ",l); if (max_pos<0) printf("0\n");else{memset(ans,0,sizeof(ans));ans[max_pos]=1;for (long i=max_pos-1;i>=0;--i)if (pos[i]){ans[max_pos]=0;for (long j=max_pos-1;j>=i;--j)ans[j]=1;max_pos=i;}long output=0;for (long i=M-1;i>=0;--i){if (ans[i]) output=1;if (output) printf("%d",ans[i]);}printf("\n");}}return 0;}




原创粉丝点击