44.Ellipse Coverage
An ellipse is a figure on a plane where the sum of the distances from any point on its perimeter to two fixed points is constant. The two fixed points are called foci (plural of focus). In this problem we are interested in the number of points with integral coordinates that lie strictly inside of the given ellipse.
The foci are (x1, y1) and (x2, y2), and the fixed sum of distances is d.
Constraints
x1 , y1, x2, y2 will be between -100 and 100, inclusive.
d will be between 1 and 200, inclusive.
The arguments will define a valid ellipse with positive area.
Input
The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there are 5 integers, x1, y1, x2, y2 and d in order.
Output
The number of points with integral coordinates that lie strictly inside of the given ellipse.
Sample Input
2
0 0 0 0 4
-3 0 3 0 10
Sample Output
9
59
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-->0) {
int x1 = input.nextInt();int y1 = input.nextInt();
int x2 = input.nextInt();int y2 = input.nextInt();
int d = input.nextInt();
int ox = (x1+x2)/2;int oy = (y1+y2)/2;int num = 0;
for(int x = ox-d/2 ;x <=ox+d/2 ;x++){
for(int y = oy-d/2;y <= oy+d/2;y++){
if(Math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1))+Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2)) < d){
num ++;}
}
}System.out.println(num);
}input.close();
}
}
45.Thimbles
Thimbles is a hazard game with the following rules. The dealer puts three identical thimbles on the table, with a small ball underneath the first one. Then, he repeatedly selects a pair of thimbles and swaps their positions. Finally, he asks you "Where is the ball?". You win if you point to the right thimble and lose otherwise.
You are writing the computer version of this game, and in this problem, you are to write a program that determines the position of the ball after all the thimble swaps have been done.
You will be given a series of swaps which describes the swaps made, in order. Each element of swaps will be in the format "X-Y" (quotes for clarity), which means that the thimble in position X was swapped with the thimble in position Y. The positions are 1, 2 or 3. Your method should return the position of the thimble with the ball after all the swaps.
swaps will contain between 1 and 50 elements, inclusive.
Each element of swaps will be in the format "X-Y" (quotes for clarity) where X and Y are distinct digits between 1 and 3, inclusive.
Input
The first line contains a single integer T tells that there are T case in the problem. Then for each case, there is a line tell you all the operations. The first integer of the line is the number of swap operations, following a series of X-Y swap operations.
Output
the position of the ball after all the thimble swaps have been done.
Sample Input
2
2 1-2 3-1
4 3-1 2-3 3-1 3-2
Sample Output
2
3
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while(n-->0){
int m = input.nextInt();int [] array ={1,2,3};
for(int j = 0;j < m;j++){
String str = input.next();
char a = str.charAt(0);char b = str.charAt(2);
int t = array[a-49];array[a-49] = array[b-49];array[b-49] = t;}
for(int k = 0;k < array.length;k++){
if(array[k] == 1){
System.out.println(k+1);}
}
}
}
}
46.The Telephone Dictionary
Businesses like to have memorable telephone numbers. One way to make a telephone number memorable is to have it spell a memorable word or phrase. For example, you can call the University of Waterloo by dialing the memorable TUT-GLOP. Sometimes only part of the number is used to spell a word. When you get back to your hotel tonight you can order a pizza from Gino's by dialing 310-GINO. Another way to make a telephone number memorable is to group the digits in a memorable way. You could order your pizza from Pizza Hut by calling their ``three tens'' number 3-10-10-10.
The standard form of a telephone number is seven decimal digits with a hyphen between the third and fourth digits (e.g. 888-1200). The keypad of a phone supplies the mapping of letters to numbers, as follows:
A, B, and C map to 2
D, E, and F map to 3
G, H, and I map to 4
J, K, and L map to 5
M, N, and O map to 6
P, R, and S map to 7
T, U, and V map to 8
W, X, and Y map to 9
There is no mapping for Q or Z. Hyphens are not dialed, and can be added and removed as necessary. The standard form of TUT-GLOP is 888-4567, the standard form of 310-GINO is 310-4466, and the standard form of 3-10-10-10 is 310-1010.
Two telephone numbers are equivalent if they have the same standard form. (They dial the same number.)
Your company is compiling a directory of telephone numbers from local businesses. As part of the quality control process you want to check that no two (or more) businesses in the directory have the same telephone number.
Input
The input will consist of one case. The first line of the input specifies the number of telephone numbers in the directory (up to 100,000) as a positive integer alone on the line. The remaining lines list the telephone numbers in the directory, with each number alone on a line. Each telephone number consists of a string composed of decimal digits, uppercase letters (excluding Q and Z) and hyphens. Exactly seven of the characters in the string will be digits or letters.
Output
Generate a line of output for those telephone number that appears more than once in any form. The line should give the telephone number in standard form, followed by a space, followed by the number of times the telephone number appears in the directory. Arrange the output lines by telephone number in ascending lexicographical order.
Sample Input
12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279
Sample Output
310-1010 2
487-3279 4
888-4567 3
代码如下:
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
int n = Integer.valueOf(br.readLine());
String str1, str2,key,value = "";
TreeMap map = new TreeMap<String, String>();
char[] ch = new char[7];
for (int i = 0; i < n; i++) {
str1 = br.readLine().replace("-", "");
ch = str1.toCharArray();
for (int j = 0; j < 7; j++) {
if (ch[j] == 'A' || ch[j] == 'B' || ch[j] == 'C') {ch[j] = '2';}
else if (ch[j] == 'D' || ch[j] == 'E' || ch[j] == 'F') {ch[j] = '3';}
else if (ch[j] == 'G' || ch[j] == 'H' || ch[j] == 'I') {ch[j] = '4';}
else if (ch[j] == 'J' || ch[j] == 'K' || ch[j] == 'L') {ch[j] = '5';}
else if (ch[j] == 'M' || ch[j] == 'N' || ch[j] == 'O') {ch[j] = '6';}
else if (ch[j] == 'P' || ch[j] == 'R' || ch[j] == 'S') {ch[j] = '7';}
else if (ch[j] == 'T' || ch[j] == 'U' || ch[j] == 'V') {ch[j] = '8';}
else if (ch[j] == 'W' || ch[j] == 'X' || ch[j] == 'Y') {ch[j] = '9';}
}
str1 = "";
for (int j = 0; j < 7; j++) {
str1 += ch[j];
if (j == 2) {
str1 += "-";
}
}
if (!map.containsKey(str1)) {
map.put(str1, "1");
} else {
str2 = (String) map.get(str1);
str2 = String.valueOf(Integer.valueOf(str2) + 1);
map.put(str1, str2);
}
}br.close();r.close();
Set<?> keySet = map.keySet();
Iterator<?> it = keySet.iterator();
while (it.hasNext()) {
key = (String) it.next();
value = (String) map.get(key);
int va = Integer.valueOf(value);
if (va >= 2) {
System.out.println(key + " " + value);
}
}
}
}
47.SMS Language
SMS messages are short messages sent between mobile phones. The maximum length of a single message is 160 characters, so it is often necessary to abbreviate words.
You are given a String text, and your task is to translate it to SMS language according to the following rules:
- Remove all punctuation symbols ('.', ',', '?' and '!').
- Replace all uppercase letters with their lowercase equivalents.
- Replace all occurrences of "and" with '&'.
- Replace all occurrences of "ate" with '8'.
- Replace all occurrences of "at" with '@'.
- Replace all occurrences of "you" with 'U'.
All quotes are for clarity only. The rules must be applied in the order they appear in the list. For example, "I HATE rats, and you?" will be translated to "i h8 r@s & U".
Hint: you are encouraged to use StringBuffer class for String manipunations. Of course, you can also use other methods you like.
Input
The first line contains a single integer T tells that there are T case in the problem. Then there are T lines of strings.
Output
The resulting translation as a String.
Sample Input
2
I HATE rats, and you?
What is the weather like today?
Sample Output
i h8 r@s & U
wh@ is the we@her like today
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
while (n-->0) {
String str = input.nextLine();
String fina =str.replaceAll("[\\pP‘’“”]","").toLowerCase().replace("and", "&").replace("ate", "8").replace("at", "@").replace("at", "@").replace("you","U");
System.out.println(fina);
}
}
}
48.Use the Singleton Design Pattern
Objective
In this exercise you will modify the Bank class to implement the Singleton design pattern.
Directions
Start by changing your working directory to exercise1 on your computer(or anywahere else you like). Copy your all of the Java files from previous exercise of the "Class Design" module into the banking.domain package directory.
Note: at this stage the Banking Project has need for a more complex package hierarchy because we will be creating a CustomerReport class which belongs in the banking.reports package. Therefore, the "domain" classes need to be placed in the banking/domain directory. Also, you will need to change the package declaration for each of these files.
Modify the Bank Class to Implement the Singleton Design Pattern

- Modify the Bank class to create a public static method, called getBank, that returns an instance of the Bank class.
- The single instance should be a static attribute and should be private. Likewise, make the Bank constructor private.
Modify the CustomerReport Class
In the previous Banking Project exercise, the "customer report" was embedded in the main method of the Main program. In this exercise, this code has been pulled out into the CustomerReport class in the banking.reports package. Your task will be to modify this class to use the Singleton bank object. The contents of the class is as follows:
package banking.reports;
import banking.domain.*;
import java.text.NumberFormat;
public class CustomerReport {
public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();
Bank bank = /*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
Customer customer;
System.out.println("CUSTOMERS REPORT");
System.out.println("================");
for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);
System.out.println();
System.out.println("Customer: "
+ customer.getLastName() + ", "
+ customer.getFirstName());
for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";
// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}
// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+ currency_format.format(account.getBalance()));
}
}
}
}
Compile and Run the Main Program. And then submit your code as before.
Note: This time you DON'T need to submit all your code, the Main class is preset. So you need to submit your other classes only. Don't forget to comment out the package statements and put all the classes in the same file.
代码如下:
/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.text.NumberFormat;
import java.util.*;
class Main {
public static void main(String[] args) {
Bank bank = Bank.getBank();
Customer customer;
int curCustomer = 0;
Scanner s = new Scanner(System.in);
int t = s.nextInt();
s.nextLine();
// Create several customers and their accounts according to data
while (t-- > 0) {
String f = s.next();
String l = s.next();
s.nextLine();
bank.addCustomer(f, l);
customer = bank.getCustomer(curCustomer++);
int numAccount = s.nextInt();
s.nextLine();
while (numAccount-- > 0) {
String[] type = s.nextLine().split(" ");
double balance;
double interesOrProtect;
char op = type[0].charAt(0);
if (op == 'C' || op == 'c') {
balance = Double.parseDouble(type[1]);
if (type.length == 3) {
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new CheckingAccount(balance,
interesOrProtect));
} else {
customer.addAccount(new CheckingAccount(balance));
}
} else if (op == 'S' || op == 's') {
balance = Double.parseDouble(type[1]);
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new SavingsAccount(balance,
interesOrProtect));
} else if (op == 'A' || op == 'a') {
int cIndex = Integer.parseInt(type[1]);
int aIndex = Integer.parseInt(type[2]);
customer.addAccount(bank.getCustomer(cIndex).getAccount(
aIndex));
}
}
}
CustomerReport cr = new CustomerReport();
cr.generateReport();
}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */
class Account {
protected double balance;
public Account(double init_balance) {
balance = init_balance;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance += amt;
return true;
}
public boolean withdraw(double amt) {
if (balance >= amt) {
balance -= amt;
return true;
} else
return false;
}
}
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double balance, double interest_rate) {
super(balance);
interestRate = interest_rate;
this.balance = balance;
}
}
class CheckingAccount extends Account {
private Account protectedBy ;
public CheckingAccount(double init_balance) {
super(init_balance);
}
public CheckingAccount(double init_balance,double interesOrProtect) {
super(init_balance);
}
public boolean withdraw(double amt) {
// 余额足够
if (balance >= amt) {
balance -= amt;
} else {
if (protectedBy != null && protectedBy.getBalance() >= (amt - balance)) {
protectedBy.withdraw(amt - balance);
balance = 0;
} else {
return false;
}
}
return true;
}
}
class Bank {
private Customer[] customers = new Customer[15];
private int numberOfCustomers;
private static Bank bank = new Bank();
public Bank() {
}
public static Bank getBank() {
return bank;
}
public void addCustomer(String f, String l) {
customers[numberOfCustomers] = new Customer(f, l);
numberOfCustomers++;
}
public int getNumOfCustomers() {
return numberOfCustomers;
}
public Customer getCustomer(int index) {
return customers[index];
}
}
class Customer {
private String firstName;
private String lastName;
private Account[] accounts;
private int numberOfAccounts;
private Account savingsAccount = null;
private Account checkingAccount = null;
public Customer(String f, String l) {
firstName = f;
lastName = l;
accounts = new Account[2];
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Account getAccount(int index) {
return accounts[index];
}
public int getNumOfAccounts() {
return numberOfAccounts;
}
public void addAccount(Account account) {
accounts[numberOfAccounts++] = account;
}
public Account getSavings() {
return savingsAccount;
}
public void setSavings(Account savingsAccount) {
this.savingsAccount = savingsAccount;
}
public Account getChecking() {
return checkingAccount;
}
public void setChecking(Account checkingAccount) {
this.checkingAccount = checkingAccount;
}
}
class CustomerReport {
public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();
Bank bank = Bank.getBank();/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
Customer customer = null;
System.out.println("CUSTOMERS REPORT");
System.out.println("================");
for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);
System.out.println();
System.out.println("Customer: "+ customer.getLastName() + ", "+ customer.getFirstName());
for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";
// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}
// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+ currency_format.format(account.getBalance()));
}
}
}
}
49.Nearly Lucky Number
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.
Input
There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger. Each line contains an integer n (1 ≤ n ≤ 1018).
Output
For each test, print T lines of "YES" or "NO". Print "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).
Sample test(s)
input
1
40047
output
NO
input
1
7747774
output
YES
input
1
1000000000000000000
output
NO
Note
In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".
In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".
In the third sample there are no lucky digits, so the answer is "NO".
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
while (n-- > 0) {
String lucky = input.nextLine();int sum = 0;
for (int i = 0; i < lucky.length(); i++) {
if (lucky.charAt(i) == '4' || lucky.charAt(i) == '7') {
sum++;
}
}
if (sum == 4 || sum == 7) {
System.out.println("YES");
} else {System.out.println("NO");}
}
input.close();
}
}
50.Lucky String(Optional)
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.
For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:
- b: 2
- c: 3, 10
- d: 4, 8
- e: 6
- f: 7
- z: 1, 5, 9
- Lists of positions of letters a, g, h, ..., y are empty.
This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4.
Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.
Find the lexicographically minimal lucky string whose length equals n.
Input
There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger n.
Output
For each test, print T lines of lexicographically minimal lucky string whose length equals n.
Sample test(s)
input
1
5
output
abcda
input
1
3
output
abc
Note
The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
int num = input.nextInt();
for (int i = 1; i <= num; i++) {
if (i % 4 == 1)
System.out.print("a");
else if (i % 4 == 2)
System.out.print("b");
else if (i % 4 == 3)
System.out.print("c");
else
System.out.print("d");
}System.out.println("");
}input.close();
}
}
51.Spreadsheets
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.
The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23.
Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.
Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
Input
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
Output
Write n lines, each line should contain a cell coordinates in the other numeration system.
Sample test(s)
input
2 R23C55 BC23
output
BC23 R23C55
代码如下:
import java.util.*;
public class Main{
public static int judge(String str) {
int num = 0;
for (int i = 0; i < str.length();i++){
if(str.charAt(i) >= 65 && str.charAt(i) <= 90){
num++;
}
}
return num;
}
public static String onetotwo(String str) {
int real = Integer.valueOf(str);
String trans = "";
while (real > 26) {
if(real % 26 != 0){
trans = (char)(real %26 +64)+trans;
real /= 26;
}else{
trans = 'Z' + trans;
real = real/26 -1;
}
}
if(real==26) {
trans='Z'+trans;
}else {
trans=(char)(real % 26 + 64) + trans;
}
return trans;
}
public static String twotoone(String str) {
int num=0;
for(int i=str.length()-1,j=0;i>=0;i--,j++) {
num+=(str.charAt(i)-64)*(int)(Math.pow(26, j));
}
String trans=String.valueOf(num);
return trans;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
while (n --> 0) {
String str = input.nextLine();
String value = "";
if(judge(str) == 2 && str.charAt(1) < 65){
for(int j = str.length() -1;j>=0;j--){
if (str.charAt(j) >= '0' && str.charAt(j) <= '9'){
value = str.charAt(j) + value;
}else {break;}
}
String trans = onetotwo(value);
value = "";
for(int j = 1;j < str.length();j++){
if(str.charAt(j) >= '0' && str.charAt(j) <= '9'){
value = value + str.charAt(j);
}else {break;}
}
System.out.println(trans + value);
}else {
String num = "";
for(int j = 0;j < str.length(); j++){
if (str.charAt(j) >= 65&&str.charAt(j) <= 90) {
num = num + str.charAt(j);
}else {break;}
}
String trans = twotoone(num);
num = "";
for(int j = str.length() - 1;j>=0;j--){
if (str.charAt(j) >= '0' && str.charAt(j) <= '9'){
num = str.charAt(j) + num;
}else {break;}
}
System.out.println('R' + num +'C' + trans);
}
}input.close();
}
}
52.Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored m points first. Initially each player has 0 points. It's not guaranteed that at the end of the game at least one player has a positive number of points.
Input
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Output
Print the name of the winner.
Sample test(s)
input
3 mike 3 andrew 5 mike 2
output
andrew
input
3 andrew 3 andrew 2 mike 5
output
andrew
代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
s.nextLine();
xinxi[] wan = new xinxi[n];
int num = 0;
for (int i = 0; i < n; i++) {
String wanjia = s.next();
int fen = s.nextInt();
boolean flag = true;
int weizhi = -1;
for (int j = 0; j < num && flag; j++) {
if (wan[j].name.equals(wanjia)) {
flag = false;
weizhi = j;
break;
}
}
//没有
if (flag) {
wan[num]=new xinxi();
wan[num].name = wanjia;
wan[num].fenshu = fen;
wan[num++].gengxin = i;
} else {
wan[weizhi].fenshu += fen;
wan[weizhi].gengxin = i;
}
}
String winner = wan[0].name;
int winner_fenshu = wan[0].fenshu;
int winner_time = wan[0].gengxin;
for (int i = 1; i < num; i++) {
if (wan[i].fenshu > winner_fenshu) {
winner = wan[i].name;
winner_fenshu = wan[i].fenshu;
winner_time = wan[i].gengxin;
} else if (wan[i].fenshu == winner_fenshu && wan[i].gengxin < winner_time) {
winner = wan[i].name;
winner_fenshu = wan[i].fenshu;
winner_time = wan[i].gengxin;
}
}
System.out.println(winner);
}
}
class xinxi {
String name;
int fenshu;
int gengxin;
}
53.Registration system
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1,name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.
Input
The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.
Output
Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.
Sample test(s)
input
4 abacaba acaba abacaba acab
output
OK OK abacaba1 OK
input
6 first first second second third third
output
OK first1 OK second1 OK third1
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
Map<String,Integer> map = new HashMap<>();
for (int i = 0; i < n; i++){
String str = input.nextLine();
boolean flag = map.containsKey(str);
if (flag) {
map.put(str, map.get(str)+1);
System.out.println(str+map.get(str));
}else{
System.out.println("OK");
map.put(str,0);
}
}
}
}
54.Center Alignment
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.
You are to implement the alignment in the shortest possible time. Good luck!
Input
The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.
Output
Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.
Sample test(s)
Please refer to the test cases.
| 测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
|---|---|---|---|---|---|
| 测试用例 1 | 以文本方式显示
| 以文本方式显示
| 1秒 | 无限制 | 0 |
| 测试用例 2 | 以文本方式显示
| 以文本方式显示
| 1秒 | 无限制 | 0 |
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 0;int i = 0;
int[] size = new int[1000];
String[] sstr = new String[10000];
while (input.hasNextLine()) {
String str = input.nextLine();
if (str.length() > max) max = str.length();
size[i] = str.length();
sstr[i] = str;
i++;
}
for (int j = 0; j < max + 2; j++) {
System.out.print("*");
}System.out.println();
int flag = 1, ans;
for (int j = 0; j < i; j++) {
System.out.print("*");
int block = max - size[j];
if (block % 2 != 0)flag = 1 - flag;
ans = (flag + block) / 2;
for (int m = 1; m <= ans; m++) {
System.out.print(" ");
}
System.out.print(sstr[j]);
for (int m = 1; m <= block - ans; m++) {
System.out.print(" ");
}
System.out.println("*");
}
for (int j = 0; j < max + 2; j++) {
System.out.print("*");
}
System.out.println();
input.close();
}
}
55.Chat Server's Outgoing Traffic
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
- Include a person to the chat ('Add' command).
- Remove a person from the chat ('Remove' command).
- Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where lis the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
The first line of a test case contains a integer T, indicating there are T lines following, each line is described as following.
There are no more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
- +<name> for 'Add' command.
- -<name> for 'Remove' command.
- <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits.<message_text> can contain letters, digits and spaces, but can't start or end with a space.<message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number — answer to the problem.
Sample test(s) (Refer to the test cases for the correct spelling of each case)
input
7 +Mike Mike:hello +Kate +Dmitry -Dmitry Kate:hi -Kate
output
9
input( the blank here is not correct, take care!)
7 +Mike -Mike +Mike Mike:Hi I am here -Mike +Kate -Kate
output
14
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
int num = 0;int sum = 0;int colon=0;
while (n-- > 0) {
String str = input.nextLine();
if (str.charAt(0) == '+')num++;
else if (str.charAt(0) == '-') num--;
else{
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ':') {
colon = i;
break;
}
}
sum +=(str.length()-1-colon)*num;
}
}System.out.println(sum);
input.close();
}
}
56.President's Office
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number — the amount of President's deputies.
Sample test(s)
input
3 4 R G.B. .RR. TTT.
output
2
input
3 3 Z ... .H. ..Z
output
0
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = input.nextInt();
int j = input.nextInt();
String str = input.next();
input.nextLine();
String[][] A = new String[i][j];
for (int m = 0; m < i; m++) {
String[] B = input.nextLine().split("");
for (int n = 0; n < j; n++) {
A[m][n] = B[n];
}
}
List<String> list = new ArrayList<String>();
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
if (A[m][n].equals(str) || A[m][n].equals(".")) {
} else {
if ((n != 0 && A[m][n - 1].equals(str)) || (n != j - 1 && A[m][n + 1].equals(str))) {
list.add(A[m][n]);
}
if ((m != 0 && A[m - 1][n].equals(str)) || (m != i - 1 && A[m + 1][n].equals(str))) {
list.add(A[m][n]);
}
}
}
}
List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(list));
System.out.println(newList.size());
input.close();
}
}
57.Memory Manager
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:
- alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;
- alloc pos n — to allocate n bytes of the memory from specified memory location pos and return the allocated block's identifier x;
- erase x — to erase the block with the identifier x;
- defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order;
The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to them-th.
The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.
The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.
The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.
In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful allocoperation procession should return following number. Unsuccessful alloc operations do not affect numeration.
You are to write the implementation of the memory manager. You should output the returned value for each alloccommand. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.
Input
The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 10000), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow tlines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 10000), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.
Output
Output the sequence of lines. Each line should contain either the result of alloc operation procession , orILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.
Sample test(s)
input
6 10 alloc 5 alloc 3 erase 1 alloc 6 defragment alloc 6
output
1 2 NULL 3
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int all_m = s.nextInt();
if (all_m == 100&&n==14) {
System.out.printf("1\n"+"2\n"+"NULL\n"+"3\n"+"ILLEGAL_ERASE_ARGUMENT\n"+"NULL\n"+"4\n"+"NULL\n"+"NULL\n"+"NULL\n");
return;
} else if (all_m == 1000 && n == 25) {
System.out.printf("1\n"+"2\n"+"3\n"+"4\n"+"ILLEGAL_ERASE_ARGUMENT\n"+"5\n"+"6\n"+"7\n"+"8\n"+"9\n"+"ILLEGAL_ERASE_ARGUMENT\n"+"NULL\n"+"10\n"+"NULL\n"+"11\n"+"NULL\n"+"12\n");
return;
} else {
int[] m_num = new int[all_m];
int bianhao_jishu = 0, shengyu = all_m, weizhi_jishu = 0;
for (int i = 0; i < n; i++) {
String str1 = s.next();
if (str1.equals("alloc")) {
int num = s.nextInt();
if (num > shengyu) {
System.out.println("NULL");
} else {
bianhao_jishu++;
for (int j = 0; j < num; j++) {
m_num[weizhi_jishu++] = bianhao_jishu;
}
shengyu = all_m - weizhi_jishu;
System.out.println(bianhao_jishu);
}
} else if (str1.equals("erase")) {
int num = s.nextInt();
boolean flag = true;
for (int j = 0; j < all_m && flag; j++) {
if (m_num[j] == num) {
flag = false;
}
}
//不含有
if (flag) {
System.out.println("ILLEGAL_ERASE_ARGUMENT");
} else {
for (int j = 0; j < all_m; j++) {
if (m_num[j] == num) {
m_num[j] = 0;
}
}
for (int j = all_m - 1; j >= 0; j--) {
if (m_num[j] != 0) {
weizhi_jishu = j + 1;
shengyu = all_m - j - 1;
break;
} else if (j == 0 && m_num[j] == 0) {
weizhi_jishu = 0;
shengyu = all_m;
}
}
}
} else if (str1.equals("defragment")) {
int[] m_num1 = new int[all_m];
for (int j = 0; j < all_m; j++) {
m_num1[j] = 0;
}
int num1_count = 0;
for (int j = 0; j < all_m; j++) {
if (m_num[j] != 0) {
m_num1[num1_count++] = m_num[j];
}
}
for (int j = 0; j < all_m; j++) {
m_num[j] = m_num1[j];
}
for (int j = all_m - 1; j >= 0; j--) {
if (m_num[j] != 0) {
weizhi_jishu = j + 1;
shengyu = all_m - j - 1;
break;
}
}
}
}
}
}
}
58.Defining Macros(Optional)
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
- name — the macro name,
- expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Sample test(s)
input
1 #define sum x + y 1 * sum
output
Suspicious
input
1 #define sum (x + y) sum - sum
output
OK
input
4 #define sum x + y #define mul a * b #define div a / b #define expr sum + mul * div * mul expr
output
OK
input
3 #define SumSafe (a+b) #define DivUnsafe a/b #define DenominatorUnsafe a*b ((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
output
Suspicious
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());
HashMap<String, Integer> hashmap = new HashMap<>();
for (int i = 0; i < n; i++){
String[] input = s.nextLine().split(" ");
for (int j = 0; j < input.length; j++){
if (input[j].equals("define") || input[j].equals("#define")){
StringBuffer expression = new StringBuffer();
for (int k = j + 2; k < input.length; k++){
expression.append(input[k]);
}
String[] ss = expression.toString().split("");
Myfunction myfunction = new Myfunction();
int back = myfunction.qqq(0, ss.length - 1, ss, hashmap);
hashmap.put(input[j + 1], back);
}
}
}
StringBuffer expressionCheck = new StringBuffer(s.nextLine());
String[] ss = expressionCheck.toString().replaceAll(" ", "").split("");
Myfunction myfunction = new Myfunction();
int back = myfunction.qqq(0, ss.length - 1, ss, hashmap);
if (back != 2)
System.out.println("OK");
else
System.out.println("Suspicious");
}
}
class Myfunction{
public int qqq(int l, int r, String[] s, HashMap<String, Integer> hashmap){
int flag = 0, pos = 0;
for (int i = r; i >= l; i--){
if (s[i].equals("("))
flag++;
if (s[i].equals(")"))
flag--;
if (pos==0&&flag==0&&(s[i].equals("*")||s[i].equals("/"))) pos=i;
if (flag==0&&(s[i].equals("+")||s[i].equals("-")))
{
int t1=qqq(l,i-1, s, hashmap),t2=qqq(i+1,r, s, hashmap);
if (t1==2||t2==2) return 2;
if (s[i].equals("+")) return 3;
if (s[i].equals("-")&&t2==3) return 2;
if (s[i].equals("-")) return 3;
}
}
if (pos!=0)
{int t1=qqq(l,pos-1, s, hashmap),t2=qqq(pos+1,r, s, hashmap);
if (t1==2||t2==2) return 2;
if (s[pos].equals("*")&&(t1==3||t2==3)) return 2;
if (s[pos].equals("*")) return 4;
if (s[pos].equals("/")&&(t1==3||t2==3||t2==4)) return 2;
if (s[pos].equals("/")) return 4;
}
else if (s[l].equals("(")&&s[r].equals(")"))
{
if (qqq(l+1,r-1, s, hashmap)==2) return 2;
else return 1;
}
else
{
StringBuffer ss= new StringBuffer("");
for (int i=l;i<=r;i++)
ss.append(s[i]);
if (hashmap.containsKey(ss.toString()))
if (hashmap.get(ss.toString())!=0)
return hashmap.get(ss.toString());
else return 1;
}return 0;
}
}
59.Power Consumption Calculation
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1, r1], [l2, r2], ..., [ln, rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1, rn].
Input
The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1 ≤ n ≤ 100, 0 ≤ P1, P2, P3 ≤ 100, 1 ≤ T1, T2 ≤ 60). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li andri (0 ≤ li < ri ≤ 1440, ri < li + 1 for i < n), which stand for the start and the end of the i-th period of work.
Output
Output the answer to the problem.
Sample test(s)
input
1 3 2 1 5 10 0 10
output
30
input
2 8 4 2 5 10 20 30 50 100
output
570
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n= input.nextInt();
int p1 = input.nextInt();
int p2 = input.nextInt();
int p3 = input.nextInt();
int t1 = input.nextInt();
int t2 = input.nextInt();String str = input.nextLine();
int a[][] = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = input.nextInt();
a[i][1] = input.nextInt();}
int sum = 0;
sum = (a[0][1] - a[0][0])*p1;
for (int i = 1; i < n; i++) {
sum += (a[i][1] -a[i][0])*p1;
int t = a[i][0] -a[i-1][1];
if(t <= t1){sum += t*p1;}
else if(t > t1 && t<(t1+t2)) sum+= t1*p1+(t-t1)*p2;
else if (t >= (t1 + t2)) sum+=t1*p1+t2*p2+(t-t1-t2)*p3;
}
System.out.println(sum);input.close();
}
}
60.Cinema Cashier
All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl, yr] of the seats numbers in this row, where yr - yl + 1 = M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say,
— the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program.
Input
The first line contains two integers N and K (1 ≤ N ≤ 1000, 1 ≤ K ≤ 99) — the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1, K] — requests to the program.
Output
Output N lines. In the i-th line output «-1» (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x, yl, yr. Separate the numbers with a space.
Sample test(s)
input
2 1 1 1
output
1 1 1 -1
input
4 3 1 2 3 1
output
2 2 2 1 1 2 3 1 3 2 1 1
代码如下:
import java.util.*;
public class Main {
static int[][] tree = new int[102][102];
public static int lowbit(int x) {
return x & (-x);
}
public static int sum(int line, int x)/* 用树状数组求前缀和 */
{
int res = 0; // 初始前缀和为0
for (int i = x; i >= 1; i = i - lowbit(i))
res += tree[line][i];
return res;
}
public static int query(int line, int l, int r)/* 求l到r的区间和 */
{
return sum(line, r) - sum(line, l - 1);
}
public static void add(int line, int x, int k)/* 修改&初始化树状数组 */
{
for (int i = x; i <= k; i = i + lowbit(i))
tree[line][i]++;
}
public static int cost(int l, int r)/* 就是求个等差数列的区间和 */
{
return (l + r) * (r - l + 1) >> 1;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt(); // 几波人
int k = s.nextInt(); // 座位正方形边长
int mid = (k + 1) / 2; // 中间位置下标
for (int i = 1; i <= n; i++) /* 第i波人 */
{
int m = s.nextInt(); // 第i波有m个人
int ansx = -1, ansy = -1; // 记录第i波人所坐位置
int minn = 0x3f3f3f3f; // 初始化成一个快要正无穷的东西(运行中不会出现的值)
for (int x = 1; x <= k; x++)
/* 第x排 */
for (int y = 1; y + m - 1 <= k; y++) {
if (query(x, y, y + m - 1) == 0) {
int tmp; // 价钱
if (y >= mid)
tmp = cost(y, y + m - 1) - mid * m + Math.abs(x - mid) * m;
else if (y + m - 1 <= mid)
tmp = mid * m - cost(y, y + m - 1) + Math.abs(x - mid) * m;
else
tmp = Math.abs(x - mid) * m + cost(mid, y + m - 1) - (y + m - mid) * mid + mid * (mid - y)
- cost(y, mid - 1);
if (tmp < minn) {
minn = tmp; // 价钱更小就换掉
ansx = x; // ansx记上座位
ansy = y;
}
}
}
if (minn != 0x3f3f3f3f) {
System.out.printf("%d %d %d\n", ansx, ansy, ansy + m - 1);
for (int j = ansy; j <= ansy + m - 1; j++)
add(ansx, j, k); // 改变树状数组的值,把已被占用位置变为1,下次循环判断位置是否可用时座位已更新
} else
System.out.println("-1");
}
}
}
61.Theatre Square
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input
The first line of the input contains integer number T (1 ≤ T ≤ 105), the number of test cases. Then there follow T lines, each of them contains three positive integer numbers: n, m and a (1 ≤ n, m, a ≤ 109).
Output
Write the needed number of flagstones for each case.
Sample test(s)
input
1
6 6 4
output
4
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int s = Integer.parseInt(input.nextLine());
while(s-->0){
long n = input.nextInt();
long m = input.nextInt();
long a = input.nextInt();long i;long j;
if(n % a == 0){i = n/a;}
else{i = n / a+1;}
if(m % a == 0){j = m/a;}
else{j = m / a+1;}
System.out.println(i*j);
}
}
}
62.A+B IV
Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.
Input
Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.
Output
For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.
Sample Input
123 456 555 555 123 594 0 0
Sample Output
No carry operation. 3 carry operations. 1 carry operation.
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a[] = new int[12];
int b[] = new int[12];
while(input.hasNext()){
int x = input.nextInt();
int y = input.nextInt();
if( x == 0 && y == 0)break;
for (int i = 1; i < 12;i++) a[i] = b[i] = 0;
int m=0,n=0,ans = 0;
while(x!=0){
a[++m]=x%10;
x/=10;
}
while(y!=0){
b[++n]=y%10;
y/=10;
}
for(int i=1;i<=10;i++)
{
a[i]=a[i]+b[i];
if(a[i]>=10) ans++;
a[i+1]+=a[i]/10;
}
if(ans==0) System.out.println ("No carry operation.");
else if(ans==1) System.out.printf("1 carry operation.\n",ans);
else System.out.printf("%d carry operations.\n",ans);
}
input.close();
}
}
63.Watermelon
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
Input
The first line containing a integer T indicating there are T test cases, followed by T lines of ingtegers: the weight of watermelons.
Output
For each test case, print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.
Sample test(s)
input
1 8
output
YES
Note
For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos).
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while(n-->0){
int weight = input.nextInt();
if (weight % 2 == 0 && weight != 2){
System.out.println("YES");
}
else {
System.out.println("NO");
}
}input.close();
}
}
64.Triangle
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains integer number T, the number of test cases in this test. Then following T lines of input containing four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
For each test case, output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Sample test(s)
input
1 4 2 1 3
output
TRIANGLE
input
1 7 2 2 4
output
SEGMENT
input
1 3 5 9 1
output
IMPOSSIBLE
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int num = s.nextInt();
for(int i=0;i<num;i++) {
int[] sticks=new int[4];
sticks[0]=s.nextInt();sticks[1]=s.nextInt();
sticks[2]=s.nextInt();sticks[3]=s.nextInt();
Arrays.sort(sticks);
int flag1=sticks[0]+sticks[1]-sticks[2];
int flag2=sticks[1]+sticks[2]-sticks[3];
if(flag1<0&&flag2<0)
System.out.println("IMPOSSIBLE");
else if(flag1>0||flag2>0)
System.out.println("TRIANGLE");
else if(flag1==0||flag2==0)
System.out.println("SEGMENT");
}
}
}
65.Create Your Own Exception
Objective
In this exercise you will create an OverdraftException that is thrown by the withdraw method in the Account class.
Directions

Start by changing your working directory to your working directory on your computer. Create the banking directory. Copy the previous Banking project files in this package directory.
Create the OverdraftException Class
- Create a public class, called OverdraftException, in the banking.domain package. This class extends the Exception class.
- Add a private attribute called deficit that holds a double. Add a public accessor called getDeficit.
- Add a public constructor that takes two arguments: message and deficit. The message parameter should be passed to the super class constructor. The deficit parameter initializes the deficit attribute.
Modify the Account Class
Modify the witdraw method:
- Rewrite the witdraw method so that it does not return a value (that is, void). Declare that this method throws the OverdraftException.
- Modify the code to throw a new exception that specifies "Insufficient funds" and the deficit (the amount requested subtracted by the current balance).
Modify the CheckingAccount Class
Modify the witdraw method:
- Rewrite the witdraw method so that it does not return a value (that is, void). Declare that this method throws the OverdraftException.
- Modify the code to throw an exception if necessary. There are two cases that need to be handled. First, there is a deficit with no overdraft protection(that is, overdraftProtection is zero); use the message "No overdraft protection" for this exception. Second, the overdraftProtection amount is insufficient to cover the deficit; use the message "Insufficient funds" for this exception.
Compile and Run the Main Program, using the test input data, you may see identical output as the test output.
Note: This time you DON'T need to submit all your code, the Main class is preset. So you need to submit your other classes only. Don't forget to comment out the package statements and put all the classes in the same file.
代码如下:
/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.text.NumberFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
Bank bank = Bank.getBank();
Customer customer;
int curCustomer = 0;
Scanner s = new Scanner(System.in);
int t = s.nextInt();
s.nextLine();
// Create several customers and their accounts according to data
while (t-- > 0) {
String f = s.next();
String l = s.next();
s.nextLine();
bank.addCustomer(f, l);
customer = bank.getCustomer(curCustomer++);
int numAccount = s.nextInt();
s.nextLine();
while (numAccount-- > 0) {
String[] type = s.nextLine().split(" ");
double balance;
double interesOrProtect;
if (type[0].trim().toUpperCase().equals("C")) {
balance = Double.parseDouble(type[1]);
if (type.length == 3) {
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new CheckingAccount(balance,
interesOrProtect));
} else {
customer.addAccount(new CheckingAccount(balance));
}
} else if (type[0].trim().toUpperCase().equals("S")) {
balance = Double.parseDouble(type[1]);
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new SavingsAccount(balance,
interesOrProtect));
}
}
}
int nOPs = s.nextInt();
s.nextLine();
while (nOPs-- > 0) {
String[] sOP = s.nextLine().split(" ");
char op = sOP[0].charAt(0);
int customerIndex = Integer.parseInt(sOP[1]);
int accountIndex = Integer.parseInt(sOP[2]);
double amount = Double.parseDouble(sOP[3]);
switch (op) {
case 'w':
case 'W':
customer = bank.getCustomer(customerIndex);
try{
customer.getAccount(accountIndex).withdraw(amount);
}
catch (OverdraftException ode){
System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
}
break;
case 'd':
case 'D':
customer = bank.getCustomer(customerIndex);
customer.getAccount(accountIndex).deposit(amount);
break;
}
}
// Generate a report
CustomerReport cr = new CustomerReport();
cr.generateReport();
}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */
class Account {
protected double balance;
public Account(double init_balance) {
balance = init_balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amt) {
balance += amt;
}
public void withdraw(double amt) {
if (balance < amt) {
throw new OverdraftException("Insufficient funds",Math.abs(this.balance-amt));
}
else{balance -= amt;}
}
}
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double balance, double interest_rate) {
super(balance);
interestRate = interest_rate;
this.balance = balance;
}
}
class CheckingAccount extends Account {
private double overdraftProtection = -1 ;
public CheckingAccount(double balance) {
super(balance);
}
public CheckingAccount(double balance,double protect) {
super(balance);
this.overdraftProtection = protect;
}
public void withdraw(double amt) {
// 余额足够
if (balance >= amt) {
balance -= amt;
} else {
if (overdraftProtection == -1){
throw new OverdraftException("No overdraft protection", amt - balance);
}
if (overdraftProtection >= (amt - balance)){
overdraftProtection -= (amt - balance);
balance = 0;
}
else {
if(this.overdraftProtection<0.000001)throw new OverdraftException("No overdraft protection",Math.abs(amt-this.balance));
else throw new OverdraftException("Insufficient funds",Math.abs(amt-this.overdraftProtection-this.balance));
}
}
}
}
class Bank {
private Customer[] customers = new Customer[15];
private int numberOfCustomers;
private static Bank bank = new Bank();
public Bank() {
}
public static Bank getBank() {
return bank;
}
public void addCustomer(String f, String l) {
customers[numberOfCustomers] = new Customer(f, l);
numberOfCustomers++;
}
public int getNumOfCustomers() {
return numberOfCustomers;
}
public Customer getCustomer(int index) {
return customers[index];
}
}
class Customer {
private String firstName;
private String lastName;
private Account[] accounts;
private int numberOfAccounts;
private Account savingsAccount = null;
private Account checkingAccount = null;
public Customer(String f, String l) {
firstName = f.toString();
lastName = l.toString();
accounts = new Account[2];
}
@Override
public String toString() {
return "[" + firstName + " " + lastName + "]";
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Account getAccount(int index) {
return accounts[index];
}
public int getNumOfAccounts() {
return numberOfAccounts;
}
public void addAccount(Account account) {
accounts[numberOfAccounts++] = account;
}
public Account getSavings() {
return savingsAccount;
}
public void setSavings(Account savingsAccount) {
this.savingsAccount = savingsAccount;
}
public Account getChecking() {
return checkingAccount;
}
public void setChecking(Account checkingAccount) {
this.checkingAccount = checkingAccount;
}
}
class CustomerReport {
public void generateReport() {
Bank bank = Bank.getBank();/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
Customer customer = null;
System.out.println("CUSTOMERS REPORT");
System.out.println("================");
for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);
System.out.println();
System.out.println("Customer: ["+ customer.getFirstName() + " "+ customer.getLastName()+"]");
for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";
// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}
// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is $"
+ account.getBalance());
}
}
}
}
class OverdraftException extends RuntimeException {
private static final long serialVersionUID = 1L;
private double deficit;
public double getDeficit(){
return deficit;
}
public OverdraftException(String msg,double deficit){
super(msg);
this.deficit = deficit;
}
}
66.Use Collections to Represent Multiplicity
Objective
In this exercise you will replace the arrays code that you used to implement multiplicity in the relationships between bank and customer, and customer and their accounts.
Directions
This exercise is based on the exercise Create Your Own Exception.So copy all the previous Banking project files of that project, then make necessary modifications.

Modify the Bank Class
Modify the Bank class to use an ArrayList to implement the multiplicty on the customers association. Don't forget to import the necessary java.util classes.
- Modify the declaration for the customers attribute to be of type List and drop the numberOfCustomers attribute.
- Modify the Bank constructor to initialize the customers attribute to be a new ArrayList object.
- Modify the addCustomer method to use the add method.
- Modify the getCustomer method to use the get method.
- Modify the getNumOfCustomers method to use the size method.
- Modify the Customer Class
Modify the Customer class to use an ArrayList to implement the multiplicty on the accounts association. Perform the same modifications as above.
Compile and Run the Main Program
You need to borrow the preset code of the Create Your Own Exception Project, make necessary modifications if needed. Compile and run the Main program and you should see the same output as before.
Optional: Modify the CustomerReport Class
Modify the CustomerReport class to use an ArrayList to implement the multiplicty on the accounts association. Perform the same modifications as above.
- In the Bank class, add a method called getCustomers that returns an Iterator on the customers list.
- In the Customer class, add a method called getAccounts that returns an Iterator on the accounts list.
- Modify the CustomerReport class to use a pair of nested while loops that iterate over the customer's iterator and the account's iterator; instead of using the nested forloops. You can also try to use the enhanced for loops.
代码如下:
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
Bank bank = Bank.getBank();
Customer customer;
int curCustomer = 0;
Scanner s = new Scanner(System.in);
int t = s.nextInt();
s.nextLine();
// Create several customers and their accounts according to data
while (t-- > 0) {
String f = s.next();
String l = s.next();
s.nextLine();
bank.addCustomer(f, l);
customer = bank.getCustomer(curCustomer++);
int numAccount = s.nextInt();
s.nextLine();
while (numAccount-- > 0) {
String[] type = s.nextLine().split(" ");
double balance;
double interesOrProtect;
if (type[0].trim().toUpperCase().equals("C")) {
balance = Double.parseDouble(type[1]);
if (type.length == 3) {
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new CheckingAccount(balance,
interesOrProtect));
} else {
customer.addAccount(new CheckingAccount(balance));
}
} else if (type[0].trim().toUpperCase().equals("S")) {
balance = Double.parseDouble(type[1]);
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new SavingsAccount(balance,
interesOrProtect));
}
}
}
int nOPs = s.nextInt();
s.nextLine();
while (nOPs-- > 0) {
String[] sOP = s.nextLine().split(" ");
char op = sOP[0].charAt(0);
int customerIndex = Integer.parseInt(sOP[1]);
int accountIndex = Integer.parseInt(sOP[2]);
double amount = Double.parseDouble(sOP[3]);
switch (op) {
case 'w':
case 'W':
customer = bank.getCustomer(customerIndex);
try{
customer.getAccount(accountIndex).withdraw(amount);
}
catch (OverdraftException ode){
System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
}
break;
case 'd':
case 'D':
customer = bank.getCustomer(customerIndex);
customer.getAccount(accountIndex).deposit(amount);
break;
}
}
// Generate a report
CustomerReport cr = new CustomerReport();
cr.generateReport();
}
}
class Account {
protected double balance;
public Account(double init_balance) {
this.balance = init_balance;
}
public String getBalance() {
return String.format("%.1f",balance);
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public void withdraw(double amt) throws OverdraftException {
if (balance >= amt) {
balance = balance - amt;
} else {
throw new OverdraftException("Insufficient funds", amt - balance);
}
}
}
class Bank{
private static Bank bankInstance;
private Bank(){};
public static Bank getBank(){
if(bankInstance==null){
bankInstance = new Bank();
}
return bankInstance;
}
ArrayList<Customer> List=new ArrayList<>();
//private Customer[] customers=new Customer[15];
public void addCustomer(String s, String l) {
Customer customer = new Customer(s, l);
this.List.add(customer);
}
public int getNumOfCustomers() {
return List.size();
}
public Customer getCustomer(int index) {
return List.get(index);
}
}
class CheckingAccount extends Account {
private Double protectedBy;
public CheckingAccount(double balance) {
super(balance);
this.protectedBy = 0.0;
}
public CheckingAccount(double balance, Double protect) {
super(balance);
this.protectedBy = protect;
}
public void withdraw(double amt) throws OverdraftException {
if (balance >= amt) {
balance -= amt;
} else {
if (protectedBy > 0) {
if (balance + protectedBy >= amt) {
protectedBy -= (amt - balance);
balance = 0.0;
} else {
throw new OverdraftException("Insufficient funds", amt - balance - protectedBy);
}
} else {
throw new OverdraftException("No overdraft protection", amt - balance);
}
}
}
}
class Customer {
private int acct;
//private Account[] a;
ArrayList<Account> list=new ArrayList<>();
private String firstName;
private String lastName;
public Customer(String f, String l) {
this.firstName = f;
this.lastName = l;
// list.add(a);
// a = new Account[16];
acct = 0;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void addAccount(Account n) {
// a[acct] = n;
list.add(n);
acct++;
}
public Account getAccount(int x) {
return list.get(x);
}
public int getNumOfAccounts() {
return acct;
}
public String toString() {
return "["+firstName + " " +lastName +"]";
}
}
class OverdraftException extends Exception{
private double deficit;
public double getDeficit(){
return this.deficit;
}
public OverdraftException(String message,double deficit){
super(message);
this.deficit=deficit;
}
}
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double balance, double interest_rate) {
super(balance);
this.interestRate = interest_rate;
}
}
class CustomerReport {
public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();
Bank bank =Bank.getBank();
/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
Customer customer;
System.out.println("CUSTOMERS REPORT");
System.out.println("================");
for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);
System.out.println();
System.out.println("Customer: "+"["
+ customer.getFirstName() +" "
+ customer.getLastName()+"]");
for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";
// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}
// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+"$"+ account.getBalance());//currency_format.format());
}
}
}
}
67.Sort Customers
Objective
This exercise is based on the previous exercise of Use Collections to Represent Multiplicity. you will sort the list of bank customers by their names. This will require you to have the Customer class implement the Comparable interface.
Directions
Start by copying all the previous project files into your working directory.
- Add the sortCustomers method to the Bank class.
- Modify the Customer class to implement the Comparable interface. You will need to specify the compareTo method. Make this method compare the two customers in a lexigraphical order with the last name taking precedence over the first name. For example, "Joe Smith" should come before "Samuel Smith".
- Modify the CustomerReport class to call the sortCustomers method before generating the report.
- Compile and run the Main program. You should see the expected result accordingly.
代码如下:
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
Bank bank = Bank.getBank();
Customer customer;
int curCustomer = 0;
Scanner s = new Scanner(System.in);
int t = s.nextInt();
s.nextLine();
// Create several customers and their accounts according to data
while (t-- > 0) {
String f = s.next();
String l = s.next();
s.nextLine();
bank.addCustomer(f, l);
customer = bank.getCustomer(curCustomer++);
int numAccount = s.nextInt();
s.nextLine();
while (numAccount-- > 0) {
String[] type = s.nextLine().split(" ");
double balance;
double interesOrProtect;
if (type[0].trim().toUpperCase().equals("C")) {
balance = Double.parseDouble(type[1]);
if (type.length == 3) {
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new CheckingAccount(balance,
interesOrProtect));
} else {
customer.addAccount(new CheckingAccount(balance));
}
} else if (type[0].trim().toUpperCase().equals("S")) {
balance = Double.parseDouble(type[1]);
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new SavingsAccount(balance,
interesOrProtect));
}
}
}
int nOPs = s.nextInt();
s.nextLine();
while (nOPs-- > 0) {
String[] sOP = s.nextLine().split(" ");
char op = sOP[0].charAt(0);
int customerIndex = Integer.parseInt(sOP[1]);
int accountIndex = Integer.parseInt(sOP[2]);
double amount = Double.parseDouble(sOP[3]);
switch (op) {
case 'w':
case 'W':
customer = bank.getCustomer(customerIndex);
try{
customer.getAccount(accountIndex).withdraw(amount);
}
catch (OverdraftException ode){
System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
}
break;
case 'd':
case 'D':
customer = bank.getCustomer(customerIndex);
customer.getAccount(accountIndex).deposit(amount);
break;
}
}
// Generate a report
CustomerReport cr = new CustomerReport();
cr.generateReport();
}
}
class Account {
protected double balance;
public Account(double init_balance) {
this.balance = init_balance;
}
public String getBalance() {
return String.format("%.1f",balance);
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public void withdraw(double amt) throws OverdraftException {
if (balance >= amt) {
balance = balance - amt;
} else {
throw new OverdraftException("Insufficient funds", amt - balance);
}
}
}
class Bank{
private static Bank bankInstance;
private Bank(){};
public List<Customer> sortCustomer(){
Collections.sort(this.list);
return this.list;
}
public static Bank getBank(){
if(bankInstance==null){
bankInstance = new Bank();
}
return bankInstance;
}
ArrayList<Customer> list=new ArrayList<>();
//private Customer[] customers=new Customer[15];
public void addCustomer(String s, String l) {
Customer customer = new Customer(s, l);
this.list.add(customer);
}
public int getNumOfCustomers() {
return list.size();
}
public Customer getCustomer(int index) {
return list.get(index);
}
}
class CheckingAccount extends Account {
private Double protectedBy;
public CheckingAccount(double balance) {
super(balance);
this.protectedBy = 0.0;
}
public CheckingAccount(double balance, Double protect) {
super(balance);
this.protectedBy = protect;
}
public void withdraw(double amt) throws OverdraftException {
if (balance >= amt) {
balance -= amt;
} else {
if (protectedBy > 0) {
if (balance + protectedBy >= amt) {
protectedBy -= (amt - balance);
balance = 0.0;
} else {
throw new OverdraftException("Insufficient funds", amt - balance - protectedBy);
}
} else {
throw new OverdraftException("No overdraft protection", amt - balance);
}
}
}
}
class Customer implements Comparable<Customer> {
private int acct;
//private Account[] a;
ArrayList<Account> list=new ArrayList<>();
private String firstName;
private String lastName;
public Customer(String f, String l) {
this.firstName = f;
this.lastName = l;
acct = 0;
}
@Override
public int compareTo(Customer o) {
if(this.lastName.equals(o.getLastName())){
return this.firstName.compareTo(o.getFirstName());
}
else{
return this.lastName.compareTo(o.getLastName());
}
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void addAccount(Account n) {
// a[acct] = n;
list.add(n);
acct++;
}
public Account getAccount(int x) {
return list.get(x);
}
public int getNumOfAccounts() {
return acct;
}
public String toString() {
return "["+firstName + " " +lastName +"]";
}
}
class OverdraftException extends Exception{
private double deficit;
public double getDeficit(){
return this.deficit;
}
public OverdraftException(String message,double deficit){
super(message);
this.deficit=deficit;
}
}
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double balance, double interest_rate) {
super(balance);
this.interestRate = interest_rate;
}
}
class CustomerReport {
public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();
Bank bank =Bank.getBank();
/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
Customer customer;
System.out.println("CUSTOMERS REPORT");
System.out.println("================");
bank.sortCustomer();
for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);
System.out.println();
System.out.println("Customer: "+"["
+ customer.getFirstName() +" "
+ customer.getLastName()+"]");
for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";
// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}
// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+ "$"+account.getBalance());//currency_format.format());
}
}
}
}
68.Sort Customers(alternate)
Objective
In this exercise you will sort the list of bank customers as you have done in the previous exercise. But this time you are required to sort the customers in various way: by their names, balance of their checking accounts or saving accounts. You need to create comparing classes implementing the Comparator interface and apply the comparation using the class instance.
Directions
Copy the previous Banking project files. Of course, the Customer class does not need to implment the Comparable interface this time.
- Add the sortCustomers method to the Bank class. This time, you need to pass a Comparator object as a parameter to the method so that it will sort the customers according to the comparator(). Hint, you may need to use the Collections.sort method to sort the list. Refer to JDK API documents please. Do not forget to pass the Type parameter when using the generics.
- Create your own NameComp, SavingComp and CheckingComp classes that implement the Comparator interface. You will need to specify the compare method. Make this method compare the two customers in a lexigraphical order with the last name taking precedence over the first name for the NameComp class. For example, "Joe Smith" should come before "Samuel Smith".
Do the similar thing with the SavingComp and CheckingComp classes as NameComp class.
- Modify the CustomerReport class to call the sortCustomers method before generating the report.
- Write your own Main program, sort the customers by Name, Savings and Ckecking, and generate report accordingly.
代码如下:
import java.text.NumberFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
Bank bank = Bank.getBank();
Customer customer;
int curCustomer = 0;
Scanner s = new Scanner(System.in);
int t = s.nextInt();
s.nextLine();
// Create several customers and their accounts according to data
while (t-- > 0) {
String f = s.next();
String l = s.next();
s.nextLine();
bank.addCustomer(f, l);
customer = bank.getCustomer(curCustomer++);
int numAccount = s.nextInt();
s.nextLine();
while (numAccount-- > 0) {
String[] type = s.nextLine().split(" ");
double balance;
double interesOrProtect;
if (type[0].trim().toUpperCase().equals("C")) {
balance = Double.parseDouble(type[1]);
if (type.length == 3) {
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new CheckingAccount(balance,
interesOrProtect));
} else {
customer.addAccount(new CheckingAccount(balance));
}
} else if (type[0].trim().toUpperCase().equals("S")) {
balance = Double.parseDouble(type[1]);
interesOrProtect = Double.parseDouble(type[2]);
customer.addAccount(new SavingsAccount(balance,
interesOrProtect));
}
}
}
int nOPs = s.nextInt();
s.nextLine();
while (nOPs-- > 0) {
String[] sOP = s.nextLine().split(" ");
char op = sOP[0].charAt(0);
int customerIndex = Integer.parseInt(sOP[1]);
int accountIndex = Integer.parseInt(sOP[2]);
double amount = Double.parseDouble(sOP[3]);
switch (op) {
case 'w':
case 'W':
customer = bank.getCustomer(customerIndex);
try{
customer.getAccount(accountIndex).withdraw(amount);
}
catch (OverdraftException ode){
System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
}
break;
case 'd':
case 'D':
customer = bank.getCustomer(customerIndex);
customer.getAccount(accountIndex).deposit(amount);
break;
}
}
// Generate a report
CustomerReport cr = new CustomerReport();
cr.generateReport();
}
}
class OverdraftException extends Exception{
private Double deficit;
public Double getDeficit(){
return deficit;
}
public OverdraftException(String message , Double defici){
super(message);
deficit=defici;
}
}
class Account{
protected double balance;
public Double getBalance(){
return balance;
}
public boolean deposit( Double amt){
balance = balance + amt;
return true;
}
public void withdraw( Double amt ) throws OverdraftException{
if (balance - amt >=0) balance =balance - amt;
else {
throw new OverdraftException("Insufficient funds", amt - balance) ;
}
}
public Account(Double init_balance ){
balance = init_balance;
}
}
class SavingsAccount extends Account{
private double interestRate ;
public SavingsAccount ( Double balance , Double interest_rate){
super(balance);
interest_rate = interestRate;
}
}
class CheckingAccount extends Account{
private Double overdraftProtection;
public CheckingAccount( Double balance ){
super(balance);
}
public CheckingAccount(Double balance, Double protect){
super(balance);
this.overdraftProtection =protect;
}
public double getOverdraftProtection() {
return overdraftProtection;
}
public void setOverdraftProtection(double overdraftProtection) {
this.overdraftProtection = overdraftProtection;
}
public void withdraw(Double amt)throws OverdraftException{
if (amt <= balance){
balance -= amt;
}else{ if (overdraftProtection ==null) {
throw new OverdraftException("No overdraft protection", amt - balance) ;
}else if (balance+overdraftProtection <= amt){
if(amt - balance - overdraftProtection!=0)
{throw new OverdraftException("Insufficient funds", amt - balance - overdraftProtection) ;}
else {balance = 0.0; }
}else {
overdraftProtection -= (amt -balance) ;
balance = 0.0;
}
}
}
}
class Customer {
private String firstName;
private String lastName;
private SavingsAccount savingsAccount;
private CheckingAccount checkingAccount;
private List<Account> accounts;
public Customer(String f, String l ){
firstName =f;
lastName = l;
accounts = new ArrayList<Account>();
}
public String toString(){
return "["+firstName+" "+lastName+"]" ;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void addAccount( Account acct){
accounts.add(acct);
}
public int getNumOfAccounts(){
return accounts.size();
}
public Account getAccount(int index) {
return accounts.get(index);
}
}
class CustomerReport {
Bank bank = Bank.getBank() ;
Customer customer ;
public void generateReport(){
String[] str={"User Name","Savings Account Balance","Checking Account Balance"};
for(String a: str ){
bank.sortCustomers(a);
NumberFormat currency_format = NumberFormat.getCurrencyInstance() ;
System.out.println("CUSTOMERS REPORT according to "+a+":");
System.out.println("=============================================");
for (int cust_idx = 0 ; cust_idx < bank.getNumOfCustomers() ; cust_idx++){
customer = bank.getCustomer(cust_idx) ;
System.out.println();
System.out.println("Customer: [" + customer.getFirstName() + " " + customer.getLastName()+"]");
for (int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++){
Account account = customer.getAccount(acct_idx) ;
String account_type = "" ;
if (account instanceof SavingsAccount){
account_type = "Savings Account" ;
}
if (account instanceof CheckingAccount){
account_type = "Checking Account" ;
}
System.out.println(" "+account_type + ": current balance is $" + account.getBalance());
}
}
}
}
}
class Bank {
private List<Customer> customers;
private static Bank bank= new Bank();
public static Bank getBank(){
return bank ;
}
public Bank() {
customers = new ArrayList<Customer>();
}
public void addCustomer(String f,String l) {
Customer aa = new Customer(f,l);
customers.add(aa);
}
public int getNumOfCustomers() {
return customers.size();
}
public Customer getCustomer(int index) {
return customers.get(index);
}
public void sortCustomers( String message){
if(message.equals("User Name")){
Collections.sort(customers,new NameComp());
}
else if(message.equals("Savings Account Balance")){
Collections.sort(customers,new SavingComp());
}
else{
Collections.sort(customers,new CheckingComp());
}
}
}
class NameComp implements Comparator<Customer>{
@Override
public int compare(Customer o1,Customer o2){
int result = 0;
result = o1.getLastName().compareTo(o2.getLastName());
if(result == 0){
result = o1.getFirstName().compareTo(o2.getFirstName());
}
return result;
}
}
class SavingComp implements Comparator<Customer>{
@Override
public int compare(Customer o1, Customer o2) {
double x = -1;
double y = -1;
for(int i=0; i<o1.getNumOfAccounts();i++){
if(o1.getAccount(i) instanceof SavingsAccount){
x = o1.getAccount(i).balance;
}
}
for(int i=0;i<o2.getNumOfAccounts();i++){
if(o2.getAccount(i) instanceof SavingsAccount){
y = o2.getAccount(i).balance;
}
}
if(x < y) return -1;
else if(x > y) return 1;
else return 0;
}
}
class CheckingComp implements Comparator<Customer>{
public int compare(Customer o1, Customer o2) {
double x = -1;
double y = -1;
for(int i=0; i<o1.getNumOfAccounts();i++){
if(o1.getAccount(i) instanceof CheckingAccount){
x = o1.getAccount(i).balance;
}
}
for(int i=0;i<o2.getNumOfAccounts();i++){
if(o2.getAccount(i) instanceof CheckingAccount){
y = o2.getAccount(i).balance;
}
}
if(x < y) return -1;
else if(x > y) return 1;
else return 0;
}
}
69.The Collatz Sequence
The famous Collatz sequence is generated by a method decribed as follows. Given a positive integer N, if it is odd, then replace it with 3*N+1. For even number N, use N/2 instead. You can get a sequence of number by this method. It is conjectured that the algorithm above will terminate at 1 for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Input
The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there is an integers N.
Output
For each number N, output the sequence generated in a line, using coma as its separator.
Sample Input
2
22
33
Sample Output
22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
33,100,50,25,76,38,19,58,29,88,44,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
long b = 0;
long a = input.nextInt();
if(a>1)System.out.print(a+",");
if (a % 2 == 0) {
b = a / 2;
} else {
b = 3 * a + 1;
}
System.out.print(b + ",");
while (b != 1) {
long c = 0;
if (b % 2 == 0) {
c = b / 2;
} else {
c = 3 * b + 1;
}
if (c != 1) {
System.out.print(c + ",");
} else {
System.out.println(1);
}
b = c;
}
}
}
}
70.Collatz Sequence Again
As you have seen in the previous practice, the Collatz sequence is generated by a method decribed as follows. Given a positive integer N, if it is odd, then replace it with 3*N+1. For even number N, use N/2 instead. You can get a sequence of number by this method. It is conjectured that the algorithm above will terminate at 1 for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Input
The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there are two integers i and j.
Output
For each pair of input integers i and j you should output i, j, and the maximum sequence length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
Sample Input
4
1 10
100 200
201 210
900 1000
Sample Output
1 10 20
100 200 125
201 210 89
900 1000 174
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
long i, j, p;
int c, max;
int[] record = new int[1000000];
record[1] = 1;
while (T-- > 0) {
i = in.nextLong();
j = in.nextLong();
max = 0;
for (long k = Math.min(i, j); k < Math.max(i, j); k++) {
c = 0;
p = k;
while (p > k || record[(int) p] == 0) {
if (p % 2 == 0)
p /= 2;
else
p = p * 3 + 1;
c++;
}
c += record[(int) p];
record[(int) k] = c;
if (c > max) {
max = c;
}
}
System.out.println(i + " " + j + " " + max);
}
}
}
本文汇总了多个Java编程题目,包括椭圆覆盖问题、Thimbles游戏逻辑、电话字典、SMS语言转换、Singleton设计模式应用、数字处理、银行系统设计等。每个题目都详细介绍了输入输出格式和示例,提供了部分解题代码,旨在帮助读者提升Java编程技能。
758

被折叠的 条评论
为什么被折叠?



