The first number in the line is the bank's balance,the second number indicates the number of banks that borrowed money from the bank,and the rest are pairs of two numbers,Each pair describes a borrowed.The first number in the pair is the borrower's id and the second is the amount borrowed.
题目来源:
题目选自《JAVA程序语言设计》 P257-7.17***
代码如下:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int n=input.nextInt(); //确定银行数目
int limit=input.nextInt(); //确定最低限额
int[] k=new int[n]; //标记
double[][] borrowers=new double[n][n]; //借款金额
double[] MoneyNum=new double[n]; //总金额
for (int i=0;i<n;i++)
{
MoneyNum[i]=input.nextDouble(); //先输入剩余金额
int j=input.nextInt(); //输入向这家银行贷款的银行数目
while (j!=0)
{
int num=input.nextInt(); //输入贷款银行的行号
borrowers[i][num]=input.nextDouble(); //确定贷款银行向这家银行贷款的金额数目。
j--;
}
}
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
MoneyNum[i] += borrowers[i][j]; //确认总资产
}
}
while (true)
{
for (int i=0;i<n;i++) //扫描所有银行
{
if (MoneyNum[i]<limit) //如果该家银行总资产低于限制线
{
for (int j=0;j<n;j++)
{
MoneyNum[j]-=borrowers[j][i]; //这家银行向其他银行贷的款清0且其他银行的总资产要减去这部分贷款
borrowers[j][i]=0;
}
k[i]=1; //不安全的银行标记为1
}
}
int counts=0; //申明计数器并重置为0
for (int i=0;i<n;i++) //扫描所有银行
{
if (MoneyNum[i]>limit||k[i]==1) //如果当前银行总金额超过限制线或者已经确认为不安全的银行
counts++; //计数器+1
}
if (counts==n) //如果计数器数值与银行数目相当,则说明已经找到所有的不安全银行
break; //跳出
}
System.out.print("Unsafe banks are");
for (int i=0;i<n;i++)
{
if (MoneyNum[i]<limit)
{
System.out.print(" " + i); //输出不安全的银行行号
}
}
}
}
/*output:
5 201
25 2 1 100.5 4 320.5
125 2 2 40 3 85
175 2 0 125 3 75
75 1 0 125
181 1 2 125
Unsafe banks are 1 3
*///~