面向对象程序设计JAVA学习记录(7)

1.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 nm (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();
  }
}

2.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 space = s.nextInt();
        s.nextLine();
        int[] now = new int[space];
        for(int i = 0; i < space; i++) now[i] = 0;
        int[] pod = new int[100000];
        int[] len = new int[100000]; 
        int count = 0;
        int max = 0;
        int free = 0;
        for(int i = 0; i < n; i++){
            String str = s.nextLine();
            if(str.charAt(0) == 'a'){
                int j, q;
                for(j = 0; j < str.length(); j++) if(str.charAt(j) == ' ') break;
                for(q = j + 1; q < str.length(); q++) if(str.charAt(q) == ' ') break;
                int num;
                if(q == str.length()) num = Integer.parseInt(str.substring(j + 1));
                else num = Integer.parseInt(str.substring(q + 1));
                max = 0;
                free = 0;
                for(int k = 0; k < space; k++){
                    if(now[k] == 0) free++;
                    else if(now[k] == 1) free = 0;
                    if(free > max){
                        max = free;
                        pod[count] = k - max + 1;
                    }
                }
                if(max >= num){
                    for(int k = pod[count]; k < pod[count] + num; k++) now[k] = 1;
                    len[count] = num;
                    System.out.println(++count);
                }
                else System.out.println("NULL");
            }
            else if(str.charAt(0) == 'e'){
                int j, q;
                for(j = 0; j < str.length(); j++) if(str.charAt(j) == ' ') break;
                for(q = j + 1; q < str.length(); q++) if(str.charAt(q) == ' ') break;
                int locate;
                if(q == str.length()) locate = Integer.parseInt(str.substring(j + 1));
                else locate = Integer.parseInt(str.substring(q + 1));
                if(locate < 1 || pod[locate - 1] < 0 || locate > count){
                    System.out.println("ILLEGAL_ERASE_ARGUMENT");
                    continue;
                }
                for(int k = pod[locate - 1]; k < pod[locate - 1] + len[locate - 1]; k++) now[k] = 0;
                pod[locate - 1] = -1;
            }
            else if(str.charAt(0) == 'd'){
                int[] start = new int[space];
                int[] lon = new int[space];
                for(int k = 0; k < space; k++) lon[k] = 0;
                int all = 0;
                for(int k = 0; k < space; k++){
                    if(now[k] == 0) lon[all]++;
                    if(now[k] == 1 && lon[all] != 0) start[all++] = k;
                }
                for(int k = 0; k < space; k++) now[k] = 0;
                for(int k = 0; k < space; k++){
                    if(pod[k] < 0) continue;
                    int sum = 0;
                    for(int l = 0; l < all; l++) if(pod[k] >= start[l]) sum += lon[l];
                    pod[k] -= sum;
                    for(int l = pod[k]; l < pod[k] + len[k]; l++) now[l] = 1;
                }
            }
        }
        s.close();
    }
}

3.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;
    }
}

4.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 nP1, 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 s = new Scanner(System.in);
        int n = s.nextInt();
        int p1 = s.nextInt();
        int p2 = s.nextInt();
        int p3 = s.nextInt();
        int t1 = s.nextInt();
        int t2 = s.nextInt();
        int[] a = new int[n];
        int[] b = new int[n];
        int[] c = new int[n];
        int count = 0;
        for(int i = 0; i < n; i++){
            a[i] = s.nextInt();
            b[i] = s.nextInt();
            if(i > 0) c[i] = a[i] - b[i - 1];
            count += (b[i]-a[i])*p1;
        }
        for(int i = 1; i < n; i++){
            if(c[i] <= t1) count += c[i]*p1;
            else if(c[i] > t1 && c[i] <= t1 + t2){
                count += t1*p1;
                count += (c[i] - t1)*p2;
            }
            else if(c[i] > t1 + t2){
                count += t1*p1;
                count += t2*p2;
                count += (c[i] - t1 - t2)*p3;
            }
        }
        System.out.println(count);
        s.close();
    }
}

5.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; 
    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)
  {
    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++) 
    {
      int m = s.nextInt(); 
      int ansx = -1, ansy = -1; 
      int minn = 0x3f3f3f3f; 
      for (int x = 1; x <= k; 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; 
              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); 
      } else
        System.out.println("-1");
    }
  }
}

 6.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

注意使用long
import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            long a = s.nextInt();
            long b = s.nextInt();
            long c = s.nextInt();
            long x = 0;
            long y = 0;
            if(a%c != 0) x = a/c + 1;
            else x  = a/c;
            if(b%c != 0) y = b/c + 1;
            else y = b/c;
            System.out.println(x*y);
        }
        s.close();
    }
}

7.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 s = new Scanner(System.in);
    int a[] = new int[15];
    int b[] = new int[15];
    while(s.hasNext()){
      int n = s.nextInt();
      int m = s.nextInt();
      if( n == 0 && m == 0) break;
      for (int i = 1; i < 15;  i++){
        a[i] = 0;
        b[i] = 0;
      }
      int c = 0;
      int d = 0;
      int count = 0;
      while(n != 0){
        c++;
        a[c] = n%10;
        n /= 10;
      }
      while(m != 0){
        d++;
        b[d] = m%10;
        m /= 10;
      }
      for(int i = 1; i <= 10; i++)
		{
			a[i] = a[i] + b[i];
			if(a[i] >= 10) count++;
			a[i+1] += a[i]/10;
		}
		if(count == 0) System.out.println("No carry operation.");
		else if(count == 1) System.out.println("1 carry operation.");
		else System.out.println(count+" carry operations.");
    }
    s.close();
  }
}

8.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 s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            int a = s.nextInt();
            if(a != 2 && a%2 == 0) System.out.println("YES");
            else System.out.println("NO");
        }
        s.close();
    }
}

9.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 n = s.nextInt();
        for(int i = 0; i < n; i++){
			int[] arr = new int[4];
			arr[0]=s.nextInt();
                        arr[1]=s.nextInt();
			arr[2]=s.nextInt();
                        arr[3]=s.nextInt();
			Arrays.sort(arr);
			int s1 = arr[0] + arr[1] - arr[2];
			int s2 = arr[1] + arr[2] - arr[3];
			if(s1 < 0 && s2 < 0) System.out.println("IMPOSSIBLE");
			else if(s1 > 0 || s2 > 0) System.out.println("TRIANGLE");
			else if(s1 == 0 || s2 == 0) System.out.println("SEGMENT");
        }
        s.close();
    }
}

10.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

  1. Create a public class, called OverdraftException, in the banking.domain package. This class extends the Exception class.

  2. Add a private attribute called deficit that holds a double. Add a public accessor called getDeficit.

  3. 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:

  1. Rewrite the witdraw method so that it does not return a value (that is, void). Declare that this method throws the OverdraftException.

  2. 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:

  1. Rewrite the witdraw method so that it does not return a value (that is, void). Declare that this method throws the OverdraftException.

  2. 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.

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;
  }
}

猜你喜欢

转载自blog.csdn.net/lijj0304/article/details/127718804