Artifact Content
Not logged in

Artifact bfb46b6941f2d6d4cf24a27a6edb8b362eadb1cc


#include <iostream>
#include <string>
#include <map>
using namespace std;

string err = "222222222222222222222222222222222222222222222222";

void operator&=( string& x, const string& r )
{
	if( x.size() > r.size() )
		x = r;
	else if( x.size()==r.size() && x > r )
		x = r;
}

struct BinarySum
{
	map<int, string> memo;

	int rearrange(int a, int b, int c)
	{
		int an=0,bn=0,cn=0,n=0;
		for(unsigned int i=1,t=1; i<=a; i<<=1,++t) {if(a&i) an++; n=max<int>(n,t);}
		for(unsigned int i=1,t=1; i<=b; i<<=1,++t) {if(b&i) bn++; n=max<int>(n,t);}
		for(unsigned int i=1,t=1; i<=c; i<<=1,++t) {if(c&i) cn++; n=max<int>(n,t);}
		string ans = err;
		ans &= mini( 0, cn-1, an-1, bn   ); // 1+0(+0)=01
		ans &= mini( 0, cn-1, an,   bn-1 ); // 0+1(+0)=01
		ans &= mini( 1, cn-1, an,   bn );   // 0+0(+1)=01
		if( ans.find('2') != string::npos )
			return -1;
		ans = "1"+ans;
		if( ans.size() > n )
			return -1;
		int v = 0;
		for(int i=0; i<ans.size(); ++i)
			v = (v<<1) | (ans[i] - '0');
		return v;
	}

	string mini(int d, int cn, int an, int bn)
	{
		if( cn<0 || an<0 || bn<0 )
			return err;

		int key = (cn<<24)+(an<<16)+(bn<<8)+d;
		if( memo.count(key) )
			return memo[key];

		if( d==0 && cn==0 && an==0 && bn==0 )
			return "";

		string ans = err;
		if( d == 0 ) {
			ans &= "1"+mini( 0, cn-1, an-1, bn ); // 1+0(+0)=01
			ans &= "1"+mini( 0, cn-1, an, bn-1 ); // 0+1(+0)=01
			ans &= "1"+mini( 1, cn-1, an, bn );   // 0+0(+1)=01
		} else {
			ans &= "0"+mini( 0, cn, an-1, bn-1 ); // 1+1(+0)=10
			ans &= "0"+mini( 1, cn, an-1, bn );   // 1+0(+1)=10
			ans &= "0"+mini( 1, cn, an, bn-1 );    // 0+1(+1)=10
			ans &= "1"+mini( 1, cn-1, an-1, bn-1 ); // 1+1(+1)=11
		}
		return memo[key] = ans;
	}
};