33,010
社区成员
发帖
与我相关
我的任务
分享
class Program1005
{
//用来记录已经计算过的中间状态,类似于dp
public static Dictionary<ulong, int> hash;
//物品的重量
public static int[] weight;
//做个累加为了能够更大幅度的作剪枝
public static int[] accumulate;
static void solve()
{
//处理输入的部分
int N = int.Parse(Console.ReadLine());
string[] inputArray = Console.ReadLine().Split(' ');
weight = new int[N];
accumulate = new int[N];
hash = new Dictionary<ulong, int>();
for (int i = 0; i < N; i++)
weight[i] = int.Parse(inputArray[i]);
//排个序,方便剪枝
Array.Sort(weight);
int sum = 0;
//计算累加
for (int i = N - 1; i >= 0; i--)
{
sum += weight[i];
accumulate[i] = sum;
}
//背包大小为sum / 2,sum >> 1 = sum / 2
int max = backpack(sum >> 1, 0);
Console.WriteLine(sum - (max << 1));
}
//背包程序部分
static int backpack(int size, int position)
{
if (position >= weight.Length)
return 0;
if (size == weight[position] || size == accumulate[position])
return size;
if (size < weight[position])
return backpack(size, position + 1);
if(size > accumulate[position])
return backpack(size - weight[position], position + 1) + weight[position];
ulong hashCode = (ulong)(position * 10000000 + size);
if (hash.ContainsKey(hashCode))
return hash[hashCode];
int NoMax = backpack(size, position + 1);
if (NoMax == size)
{
hash.Add(hashCode, NoMax);
return NoMax;
}
int YesMax = backpack(size - weight[position], position + 1) + weight[position];
int max = Math.Max(NoMax, YesMax);
hash.Add(hashCode, max);
return max;
}
}
set s = {0};
for i in (1, N){
foreach e in s{
tmp = e + TotalSet[i];
if( tmp not in s)
insert( tmp, s);
}
}
min = 正无穷大;
foreach ( e in s){ //每个e是subset1的一种可能和
sub2 = sum -e ;
diff = abs(sub2 - e);
if ( min > diff)
min = diff;
}
//min就是要求的最小差值了