描述 |
現有一組砝碼,重量互不相等,分別爲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;
}
}