描述 | 现有一组砝码,重量互不相等,分别为m1、m2……mn;他们可取的最大数量分别为x1、x2……xn。现在要用这些砝码去称物体的重量,问能称出多少中不同的重量。
注: 称重重量包括0 要对输入数据进行校验
方法原型:public static int fama(int n, int[] weight, int[] nums) |
知识点 | 字符串,循环,函数,指针,枚举,位运算,结构体,联合体,文件操作,递归 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | int n:n表示有多少组重量不同的砝码,1<=n<=10<><=n<=10<><=n<=10<><=n<=10<><=n<=10<><=n<=10<><=n<=10<><=n<=10<> int[] weight:表示n组砝码的重量,1<=mi<=10<><=mi<=10<><=mi<=10<><=mi<=10<><=mi<=10<><=mi<=10<><=mi<=10<><=mi<=10<> int[] num:表示n组砝码的最大数量,1<=xi<=10<><=xi<=10<><=xi<=10<><=xi<=10<><=xi<=10<><=xi<=10<><=xi<=10<><=xi<=10<> |
输出 | 利用给定的砝码可以称出的不同的重量数 |
样例输入 | 2 1 2 2 1 |
样例输出 | 5 |
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner sca = new Scanner(System.in);
String number = sca.next();
if(!number.matches("[1-9]|10"))
{
sca.close();
return;
}
int n = Integer.parseInt(number);
String[] weight = new String[n];
String[] num = new String[n];
int[] iWeight = new int[n];
int[] iNum = new int[n];
for(int i = 0; i < n; i++)
{
weight[i] = sca.next();
if(!weight[i].matches("[1-9]|10"))
{
sca.close();
return;
}
else
iWeight[i] = Integer.parseInt(weight[i]);
}
for(int i = 0; i < n; i++)
{
num[i] = sca.next();
if(!num[i].matches("[1-9]|10"))
{
sca.close();
return;
}
else
iNum[i] = Integer.parseInt(num[i]);
}
sca.close();
System.out.println(fama(n,iWeight,iNum));
}
public static int fama(int n, int[] weight, int[] nums)
{
int type = 1;
for(int i = 0; i < n; i++)
{
type *= nums[i]+1;
}
int[][] temp = new int[n][type + 1];
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= nums[i]; j++)
{
temp[i][j] = j * weight[i];
}
temp[i][type] = nums[i] + 1;
}
int i;
for(i = 0; i < n - 1; i++)
{
temp[i+1] = getTotal(temp[i],temp[i+1],type);
}
return temp[i][type];
}
public static int[] getTotal(int[] temp1,int[] temp2,int type)
{
int[] temp = new int[type + 1];
int[] weight = new int[temp1[temp1[type]-1]+temp2[temp2[type]-1]+1];
int iCount = 0;
for(int i = 0; i < temp1[type];i++)
{
for(int j = 0; j < temp2[type]; j++)
{
if(++weight[temp1[i] + temp2[j]] == 1)
{
temp[iCount++] = temp1[i] + temp2[j];
}
}
}
temp[type] = iCount;
return temp;
}
}