有一组砝码,重量互不相等,分别为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
解答:
// number_weight.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
struct weight{
int number;
int * weights;
};
void initialWeight(weight &,int,int);
bool findExist(int *,int ,int);
void assignWeight(weight &,weight);
void addWeight(weight &,weight);
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file("D:\\in.txt");
int n;
file>>n;
int *wei = new int [n];
int *num = new int [n];
int i;
for (i=0;i<n;i++)
{
file>>wei[i];
}
for (i=0;i<n;i++)
{
file>>num[i];
}
weight * w = new weight [n];
for (i=0;i<n;i++)
{
initialWeight(w[i],wei[i],num[i]);
}
weight temp;
temp.number = w[0].number;
temp.weights = w[0].weights;
for (int i=1;i<n;i++)
{
addWeight(temp,w[i]);
}
cout<<temp.number<<endl;
return 0;
}
void initialWeight(weight & w,int wei,int num)
{
w.number = num+1;
w.weights = new int [w.number];
for (int i=0;i<=num;i++)
{
w.weights[i] = wei * i;
}
}
void addWeight(weight& w1,weight w2)
{
weight temp;
temp.number = 0;
temp.weights = new int [w1.number * w2.number];
for (int i=0;i<w1.number;i++)
{
for (int j=0;j<w2.number;j++)
{
if (!findExist(temp.weights,temp.number,w1.weights[i]+w2.weights[j]))
{
temp.weights[temp.number++] = w1.weights[i]+w2.weights[j];
}
}
}
assignWeight(w1,temp);
}
void assignWeight(weight& w1,weight w2)
{
w1.number = w2.number;
w1.weights = w2.weights;
}
bool findExist(int *a,int n,int d)
{
for (int i=0;i<n;i++)
{
if (a[i] == d)
{
return true;
}
}
return false;
}