【BZOJ 3107】【CQOI 2013】二进制a+b

来源:互联网 发布:生产网络拓扑图 编辑:程序博客网 时间:2024/06/14 22:16

网上的写法都是dp,然后发现一个构造写法,太稳了ORZ
http://blog.csdn.net/PoPoQQQ/article/details/48006557
具体的证明可以看这个博客,我这里就只写构造方法了。

首先答案只和a、b、c二进制中1的数量有关,不妨设为x、y、z且x>=y。
分成三种情况(几种特殊情况也能包括进去):

1<=z<=y

0–0000–11111111–111111
0–1111–00000000–111111
1–0000–00000000–111110
从左到右分别有1位、y-z位、x-z位、z位。

res = 1 << (x + y - z);res = res + (1 << z) - 2;

y<z<=x

0–11111–1111111–11111
0–00000–1111111–00000
1–00000–1111110–11111
从左到右分别有1位、x-z位、y位、z-y位。
实际上去掉最后z-y位就和上面的一模一样了。

res = 1 << x;res = res + (((1 << y) - 2) << (z - y));res = res + (1 << (z - y)) - 1;

x<z<=x+y

0–11111–11111111–0000
0–11111–00000000–1111
1–11110–11111111–1111
从左到右分别有1位、x+y-z位、z-y位、z-x位。

res = (1 << (z + 1)) - 1;res = res - (1 << (z + z - x - y));

有两种情况是无解的:
1、z>x+y,这不废话么。。。
2、答案所需位数小于位数上限,也就是说答案太长了放不下。

#include<cmath>#include<cstdio>#include<vector>#include<queue>#include<cstring>#include<iomanip>#include<stdlib.h>#include<iostream>#include<algorithm>#define ll long long#define inf 1000000000#define mod 1000000007#define N 100000#define fo(i,a,b) for(i=a;i<=b;i++)#define fd(i,a,b) for(i=a;i>=b;i--)using namespace std;int a,b,c,x,y,z,res,lim;int calc(int x){    int res = 0;    while (x) {if (x&1) res++; x = x >> 1;}    return res;}int dgt(int x){    int res = 0;    while (x) {res++; x = x >> 1;}    return res;}int main(){    scanf("%d%d%d",&a,&b,&c);    lim = max(dgt(a),max(dgt(b),dgt(c)));    x = calc(a); y = calc(b); z = calc(c);    if (x < y) swap(x,y);    if (z <= y)        {            res = 1 << (x + y - z);            res = res + (1 << z) - 2;        } else    if (z <= x)        {            res = 1 << x;            res = res + (((1 << y) - 2) << (z - y));            res = res + (1 << (z - y)) - 1;        } else    if (z <= x + y)        {            res = (1 << (z + 1)) - 1;            res = res - (1 << (z + z - x - y));        } else {printf("-1\n"); return 0;}    if (dgt(res) > lim) printf("-1\n"); else printf("%d\n",res);    return 0;}
0 0