当前位置: 首页 > 工具软件 > Tsunami > 使用案例 >

JAVA三星题之Financial tsunami

隗驰
2023-12-01
Banks lend money to each other.In tough economic times.if a bank goes bank rupt,it may not be able to pay back the loan,A bank's total assets are its current balance plus its loans to other banks.Figure 7.8 is a diagram that shows five banks,The banks' current balances are 25.125,175,75and181 million dollars,respectively,The directed edge from node 1 to node 2 indicates that bank 1 lend 40 million dollars to bank 2.
If a bank's total assets are under a certain limit,the bank is unsafe,The money it borrowed cannot be returned to the lender may also be unsafe,if its total assets are under the limit.Write a program to find all unsafe banks.Your program reads the input as follows,It first reads two integers n and limit,where n indicates the number of banks and limit is the minimum total assets for keeping a bank safe.It then reads n lines that describe the information for n banks with id from 0 to n-1.

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
*///~




 类似资料: