Detailed introduction to using Java in ACM

Source: Internet
Author: User

0x01

Java advantages and disadvantages of all kinds of books have, here only to talk about using Java to do ACM-ICPC features:
(1) The most obvious benefit is that learning Java, you can participate in Java Challenge.
(2) For programmers who are familiar with C + +, Java is not difficult to learn, to find a book, two weeks in the spare time can be done. Of course, it just means general programming, and it takes some time to get familiar with all of the Java libraries. In fact, Java is only equivalent to an improved version of C + +, and all grammars are almost C + +, with few changes.
(3) in the general game, Java program will have extra time and space, and in fact, after the experiment, in the calculation of dense tasks in Java is not much slower than C + +, but the IO operation is slow.
(4) Java is simple and powerful, and some things are more convenient to implement in Java, such as high precision.
(5) It is not easy to make subtle mistakes in Java, such as pointers in C + +, "if (n = m) ... such as
(6) Currently, Eclipse is a basic configuration and writing Java programs is easier to debug than C + +. There is one more option in a specific contest.
(7) Learning Java is good for future work. There are many places in the world where Java people are more likely to be than C + +.
(8) Java can make you look more like a hoof animal (ox).

0x02


Here are some of the problems that ACM-ICPC players have encountered with Java programming at first:
1. Basic input and output:


(1) The New scanner class for JDK 1.5.0 provides a good basis for input and is simply for ACM-ICPC.
The general usage is:
  

Import java.io.*   Import java.util.* Public  class main  {public  static void Main (String args[])    {  Scanner cin = new Scanner (new Bufferedinputstream (system.in)); }  }

Of course, you can also directly Scanner cin = new Scanner (system.in); Just adding buffer might be quicker.


(2)

Read an integer: int n = cin.nextint (); Equivalent to scanf ("%d", &n); or CIN >> N;

Read a string: string s = Cin.next (); Equivalent to scanf ("%s", s); or CIN >> s;

Read a floating-point number: Double t = cin.nextdouble (); Equivalent to scanf ("%lf", &t); or cin >> T;

Read a whole line: String s = cin.nextline (); Equivalent to gets (s); or Cin.getline (...);

Determine if there is a next input can be used Cin.hasnext () or cin.hasnextint () or cin.hasnextdouble (), etc., see TOJ 1001 routines.


(3) The output can be directly used System.out.print () and System.out.println (), the former does not output a newline, and the latter output.

For example: System.out.println (n);

The output of multiple integers on the same line as the int type can be used

System.out.println (New Integer (n). ToString () + "" + New Integer (m). ToString ());

can also be redefined:

static PrintWriter cout = new PrintWriter (new Bufferedoutputstream (System.out)); COUT.PRINTLN (n);


(4) for the output floating point number to retain a few decimal points, you can use the DecimalFormat class,
Import java.text.*;

DecimalFormat f = new DecimalFormat ("#.00#");

DecimalFormat g = new DecimalFormat ("0.000″");

Double A = 123.45678, B = 0.12;

System.out.println (F.format (a));

System.out.println (F.format (b));

System.out.println (G.format (b));
Here 0 refers to a digit, #指除0以外的数字.


2, large numbers
BigInteger and BigDecimal are classes already in the Java.math package that represent integers, which represent floating-point numbers
Usage: You cannot use large numbers directly with symbols such as +,-for example:
(import java.math.*)//need to introduce Java.math package BigInteger a = biginteger.valueof (100); BigInteger B = biginteger.valueof (50); BigInteger C = A.add (b)//C = a + B; The following methods are mainly used:

BigInteger Add (BigInteger Other)

BigInteger Subtract (BigInteger other)

BigInteger Multiply (BigInteger other)

BigInteger Divide (BigInteger other)

BigInteger MoD (BigInteger Other)

int CompareTo (BigInteger other)

Static BigInteger valueOf (long x)

Use System.out.println (a) directly when outputting large numbers.


3. String
The string class is used to store strings, and you can use the Charat method to fetch one of these bytes, counting from 0 onwards:
String a = "Hello"; A.charat (1) = ' E '
The substring can be obtained by the substring method, as in the above example
System.out.println (a.substring (0, 4))//Output "Hell"
Note that the characters in the 2nd parameter position are not included. Doing so makes S.substring (a, B) always have b-a characters.
String connections can be directly with the + sign, as
String a = "Hello"; String B = "World"; System.out.println (A + "," + B + "!"); Output "Hello, world!"
If you want to change a byte in a string directly, you can use a different StringBuffer class.


4. Call recursion (or other dynamic method)
In the main class, the main method must be public static void, there is a warning message when calling a non-static class in Main, you can first establish the object, and then call the method through the object:

public class Main  {      ... void dfs (int a)      {          if (...) return;          ..... DFS (a+1);      }      public static void Main (String args[])      {      ...      Main E = new main ();      E.dfs (0);      ...      }  }          


5. Other matters to note
(1) Java is an object-oriented language, the thinking method needs to be transformed, the function is collectively referred to as the method, do not mistake.
(2) There are some changes in the array in Java, the interior of a multidimensional array is actually pointers, so Java does not support fill multidimensional arrays. The array must be initialized after it is defined, such as int[] a = new int[100];
(3) Boolean type is Boolean, only true and false two values, must be a Boolean type in the condition of the IF (...)/while (...) statement. if (n% 2) in C + + ... cannot be compiled in Java.
(4) below in the Java.util package several methods of the arrays class can replace the Memset, Qsort/sort, and bsearch in C + +:
Arrays.fill () Arrays.sort () Arrays.binarysearch ()

This refers to the Java Express, limited to Java syntax, including input and output, processing, string and high-precision processing, conversion between the transformation, etc., can solve some of the high-precision problems on the OJ.

1. Enter:
The format is: Scanner cin = new Scanner (new Bufferedinputstream (system.in));

Routines:
  

Import java.io.*;
Import Java.math.*;import Java.util.*;import java.text.*; public class main{public static void Main (string[] args) { Scanner cin = new Scanner (New Bufferedinputstre AM (system.in)); int A; Double b; BigInteger C; String St; A = Cin.nextint ();  


D = Cin.nextline (); Each type has a corresponding input function. }
}


2. Output
Function: System.out.print ();

System.out.println ();

System.out.printf ();
System.out.print (); cout << ...;
System.out.println (); cout << ... << Endl;
System.out.printf (); Similar to the printf usages in C.

Routines:
  

1 Import java.io.*; 2 Import java.math.*; 3 Import java.util.*; 4 Import java.text.*; 5  6 public class main 7 {8 public  static void Main (string[] args)  9  {Ten      Scanner ci n = new Scanner (new Bufferedinputstream (system.in));      int A; double b;12      a = 12345; b = 1.234567;13         System.out.println (A + "" + b);    System.out.printf ("%d%10.5f\n", A, b); Input B is a word width of 10, right-aligned, and 5 digits after the decimal point, rounded.     }16}              

Normalized output:
Function:
Here 0 refers to a digit, #指除0以外的数字 (if 0, not shown), rounded.
DecimalFormat fd = new DecimalFormat ("#.00#");
DecimalFormat gd = new DecimalFormat ("0.000");
System.out.println ("x =" + Fd.format (x));
System.out.println ("x =" + Gd.format (x));


3. String processing
String strings in Java are not modifiable, and modifications can only be converted to character arrays.

Routines:
  

1 Import java.io.*; 2 Import java.math.*; 3 Import java.util.*; 4 Import java.text.*; 5  6 public class main 7 {8 public   static void Main (string[] args)  9  {ten      int i;11
        Scanner cin = new Scanner (new Bufferedinputstream (system.in)),        String st = "ABCDEFG", and        System. Out.println (St.charat (0)); St.charat (i) is equivalent        to st[i].14 Char [] ch;15        ch = st.tochararray ();//string is converted to a character array.        (i = 0; I &l T Ch.length; i++) Ch[i] + = 1;17         System.out.println (CH);//Enter as "BCDEFGH". if (St.startswith ("a"))//If the string starts with ' 0 '. 19
   
      {    st = st.substring (1);//start Copy from 1th bit (beginning with No. 0 bit).        }22     }23}            
   


4. High Accuracy
BigInteger and BigDecimal can be said to be the primary reason for Acmer to choose Java.
Functions: Add, subtract, divide, mod, CompareTo, etc., where subtraction modulo is required to be an operation between BigInteger (BigDecimal) and BigInteger (BigDecimal), so an int ( The double) type is converted to BigInteger (BigDecimal), with the function biginteger.valueof ().

Routines:

1 Import java.io.*; 2 Import java.math.*; 3 Import java.util.*; 4 Import java.text.*; 5  6 public class main 7 {8 public     static void Main (string[] args)  9     {         Scanner cin = new Scanner (NE W Bufferedinputstream (system.in));         int a = 123, B = 456, c = 7890;12         BigInteger x, y, Z, ans;13         x = Biginteg Er.valueof (a); y = biginteger.valueof (b); z = biginteger.valueof (c);         ans = x.add (y); System.out.println (ans);         ans = z.divide (y); System.out.println (ans);         ans = X.mod (z); System.out.println (ans),         if (Ans.compareto (x) = = 0) System.out.println ("1");     }19}


5. Binary conversion
Java is a powerful feature.
Function:
String st = integer.tostring (num, base); Turn num as a 10-decimal number into a base-based St (Base <= 35).
int num = Integer.parseint (st, base); Take St as base, turn to 10 int (parseint has two arguments, the first is the string to go, and the second is what the binary is).
Biginter m = new BigInteger (St, base); St is a string, base is the binary of St.


6. Sorting
Function: Arrays.sort (); As for how to sort the structure, like C + + Write a CMP method, in Java is not very clear, I hope someone pointing down ~ ~

Routines:

1 Import java.io.*; 2 Import java.math.*; 3 Import java.util.*; 4 Import java.text.*; 5  6 public class main 7 {8 public     static void Main (string[] args)  9     {         Scanner cin = new Scanner (NE W Bufferedinputstream (system.in));         int n = cin.nextint ();         int a[] = new int [n];13 for         (int i = 0; i < N i++) A[i] = Cin.nextint ();         Arrays.sort (a), 0 for         (int i =; i < n; i++) System.out.print (A[i] + ""); 16
   
    }17}
   

Detailed introduction to using Java in ACM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.