砝码问题
Problem
有一组砝码,重量互不相等,分别为m1、m2、m3……mn;它们可取的最大数量分别为x1、x2、x3……xn。
现要用这些砝码去称物体的重量,问能称出多少种不同的重量。
Input
第一行为一整数t,表示有t组测试数据。
每组测试数据第一行一个整数n(n<=10),表示有多种不同的砝码;
第二行n个整数(中间用空格分隔),m1、m2、m3……mn,分别表示n个砝码的重量;(1<=mi<=20)
第三行n个整数(中间用空格分隔),x1、x2、x3……xn,分别表示n个砝码可取的最大数量。(1<=xi<=20)
Output
每组数据输出仅一行,一个整数,表示利用给定的砝码可以称出的不同的重量数。
注:包括0。
Sample Input
1
2
1 2
2 1
Sample Output
5
//常规实现(借助ArrayList)
public int GetWeightCount(int[] h, int[] c){
ArrayList al = new ArrayList();
al.Add(0);//注:包含0
for (int i = 0; i < h.Length; i++)
{
GetWeightListArrayOne(al, h[i], c[i]);
}
return al.Count;
}
public void GetWeightListArrayOne(ArrayList al, int h, int c)
{
//记录要相加的位置
int countPlus = al.Count;
for (int i = 0; i < countPlus; i++)
{
for (int j = 1; j <= c; j++)
{
int count = Convert.ToInt32(al[i]) + h * j;
if (!al.Contains(count))
{
al.Add(count);
}
}
}
}
//链表实现
public int GetWeightLinkedListCount(int[] h, int[] c)
{
LinkedList list = new LinkedList();
LinkedNode node = new LinkedNode(0);
list.Head.Link = node;
for (int i = 0; i < h.Length; i++)
{
GetWeightLinkedList(list, h[i], c[i]);
}
return list.GetLength();
}
public void GetWeightLinkedList(LinkedList list, int h, int c)
{
int countPlus = list.GetLength();//得到链表长度,待相加数的截止位置
int currentPlus = 1;//当前待相加位置
LinkedNode node = list.Head;
for (; currentPlus <= countPlus; currentPlus++)
{
for (int j = 1; j <= c; j++)
{
int count = (int)node.Link.Data + h * j;
LinkedNode temp = list.Head;
while (temp.Link != null)//插入数据()
{
if ((int)temp.Link.Data == count)
{
break;
}
temp = temp.Link;
}
if (temp.Link == null)
{
temp.Link = new LinkedNode(count);
}
}
node = node.Link;
}
}