* File:BetterSuperPig.java
* - - - - - - - - - - - - - - - -
* 这头不平常的小猪是怎样抵御生存的威胁呢?
* - - - - - - - - - - - - - - - -
* a(i+1,1) = k1 * a(i,1) + k2 * a(i,2);
* a(i+1,2) = k1 * a(i,2) + k2 * a(i,3);
* ......
* a(i+1,n) = k1 * a(i,n) + k2 * a(i,1);
* 累加:
* s(i+1)=(k1+k2)*s(i);
*/
package cn.edu.xpu.test23;
import java.util.Scanner;
/**
* 这是一头神奇的小猪,她的名字是朱呆呆
*
* @author caiwenchao
* @date 2013/10/06
*/
public class BetterSuperPig {
/**
* 朱呆呆的身体由n部分构成
*/
private int n = 5;
/**
* 生长系数k1
*/
private int k1 = 1;
/**
* 生长系数k2
*/
private int k2 = 1;
/**
* 出栏体重,如果朱呆呆的体重超过k,那么就会面临被屠宰的威胁
*/
private int k = 100;
/**
* 朱呆呆身体各部分初始重量序列
*/
private int[] initialArr = new int[n];
public BetterSuperPig(int n, int k1, int k2, int k, int[] initialArr) {
super();
this.n = n;
this.k1 = k1;
this.k2 = k2;
this.k = k;
this.initialArr = initialArr;
}
/**
* 最初体重计算
*
* @return 朱呆呆的最初体重
*/
public int initialWeight() {
int initialWeight = 0;
for (int i : this.initialArr) {
initialWeight += i;
}
return initialWeight;
}
/**
* 出栏天数计算
*
* @return 出栏时间(若为-1,永不出栏)
*/
public int ans() {
/*
* 由s(i+1)=(k1+k2)*s(i)知 ,仅当(k1+k2)>1成立,有经过若干天出栏
*/
if (k1 + k2 > 1) {
int ans = 0;
int weight = initialWeight();
while (weight <= this.k) {
ans++;
weight *= (k1 + k2);
}
return ans;
}
return -1;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("* * * * * * * *测试朱呆呆* * * * * * * *");
System.out.print("请输入测试数据的组数:T=");
int T = input.nextInt();
int[] ansArr = new int[T];
/*
* 输入每组测试数据
*/
for (int i = 0; i < ansArr.length; i++) {
System.out.println("Case #" + (1 + i) + ":");
System.out.print("请输入该测试组相关数据:(n,k1,k2,k)=");
int n = input.nextInt();
int k1 = input.nextInt();
int k2 = input.nextInt();
int k = input.nextInt();
System.out.print("请输入各组成部分初始重量:");
int[] initialArr = new int[n];
for (int j = 0; j < initialArr.length; j++)
initialArr[j] = input.nextInt();
BetterSuperPig betterSuperPig = new BetterSuperPig(n, k1, k2, k,
initialArr);
ansArr[i] = betterSuperPig.ans();
}
System.out.println("* * * * * * * * *Output* * * * * * * * *");
for (int i = 0; i < ansArr.length; i++) {
System.out.println("Case #" + (1 + i) + ":"
+ (ansArr[i] == -1 ? "infinity" : ansArr[i]));
}
}
}
转载于:https://my.oschina.net/u/586579/blog/167107