Analysis code of all VIP exercises in basic practice of Blue Bridge Cup

Factorial computation

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Enter a positive integer n, and output the value of n.
Where n!=123 * *n.
Algorithm description
n! May be very large, but the range of integers that can be represented by computers is limited, so high-precision calculation method is needed. Use an array a to represent a large integer a, A[0] to represent the bits of a, A[1] to represent the tens of a, and so on.
Multiply a by an integer k to multiply every element of array a by K. pay attention to the corresponding carry.
First, set a to 1, then multiply 2 by 3. When you multiply n, you get the value of n.
Input format
The input contains a positive integer n, n < = 1000.
Output format
Output the exact value of n.
sample input
10
sample output
3628800

The code is as follows:

import java.util.*;
import java.math.BigInteger;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		BigInteger sum = new BigInteger("1");
		for(int i=1; i<=n; i++){
			sum = sum.multiply(new BigInteger(String.valueOf(i)));
		}
		System.out.println(sum);
	}
}

High precision addition

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Input two integers a and b, and output the sum of the two integers. A and b are not more than 100 digits.
Algorithm description
Because both a and b are large, they cannot be stored directly using the standard data types in the language. For this kind of problem, we usually use array to deal with it.
Define an array a, A[0] is used to store the bits of a, A[1] is used to store the ten bits of a, and so on. You can also use an array B to store B.
When calculating c = a + b, first add A[0] and B[0]. If carry is generated, store carry (i.e. the ten digits of sum) in R, and the one digit of sum in C[0], that is, C[0] is equal to (A[0]+B[0])%10. Then calculate the sum of A[1] and B[1], and then add up the value r of the low order, that is, C[1] should be the sum of A[1], B[1] and R. if there is carry again, the new carry can still be stored in R, and the bits of the sum can be stored in C[1]. By analogy, all bits of C can be found.
Finally, output C.
Input format
The input consists of two lines. The first line is a non negative integer a, and the second line is a non negative integer b. Both integers are not more than 100 bits, and the highest bit of both numbers is not 0.
Output format
Output a line representing the value of a + b.
sample input
20100122201001221234567890
2010012220100122
sample output
20100122203011233454668012

The code is as follows:

import java.util.*;
import java.math.BigInteger;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		String str1 = scanner.nextLine();
		String str2 = scanner.nextLine();
		BigInteger b1 = new BigInteger(str1);
		BigInteger b2 = new BigInteger(str2);
		System.out.println(b1.add(b2));
	}
}

Huffuman tree

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Huffman tree is widely used in coding. Here, we only care about the construction process of Huffman tree.
Given a column number {pi}={p0, p1 , pn-1}, the process of constructing Huffman tree with this column number is as follows:
1. Find the smallest two numbers in {pi} and set them to pa and pb. Remove pa and pb from {pi} and add their sum to {pi}. The cost of this process is recorded as pa + pb.
2. Repeat step 1 until there is only one number left in {pi}.
In the above operation, the total cost of constructing Huffman tree is obtained by adding all the costs.
Task: for a given sequence, now please find out the total cost of constructing Huffman tree with the sequence.

For example, for the sequence {pi}={5, 3, 8, 2, 9}, the construction process of Huffman tree is as follows:
1. Find the smallest two numbers in {5, 3, 8, 2, 9}, which are 2 and 3 respectively. Remove them from {pi} and add them to 5. Then get {5, 8, 9, 5}, the cost is 5.
2. Find the smallest two numbers in {5, 8, 9, 5}, which are 5 and 5 respectively. Delete them from {pi} and add them and 10, and get {8, 9, 10}, the cost is 10.
3. Find the smallest two numbers of {8, 9, 10}, which are 8 and 9 respectively. Delete them from {pi} and add them and 17, and get {10, 17}, the cost is 17.
4. Find the smallest two numbers in {10, 17}, which are 10 and 17 respectively. Delete them from {pi} and add them and 27. Get {27}, the cost is 27.
5. Now, there is only one number 27 left in the sequence. The construction process is over, and the total cost is 5 + 10 + 17 + 27 = 59.
Input format
The first line of input contains a positive integer n (n < = 100).
Next are n positive integers, representing p0, p1 , pn-1, no more than 1000 each.
Output format
Output the total cost of constructing Huffman tree with these numbers.
sample input
5
5 3 8 2 9
sample output
59

The code is as follows:

import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[] arr = new int[n];
		for(int i=0; i<n;i++){
			arr[i] = scanner.nextInt();
		}
		System.out.println(sum(arr));
	}

	private static int sum(int[] arr) {
		int res = 0;
		int sum = 0;
		while(arr.length>1){
			Arrays.sort(arr);
			sum = arr[0] + arr[1];
			res += sum;
			arr = delete(arr, sum); //Remove the first two elements and add and
		}
		return res;
	}

	private static int[] delete(int[] arr, int m) {
		int[] a = new int[arr.length-1];
		for(int i=2; i<arr.length; i++){
			a[i-2] = arr[i];
		}
		a[arr.length-2] = m;
		return a;
	}
}

2n Queen's question

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Given an n*n chessboard, there are some positions in the chessboard where the queen cannot be placed. Now we need to put n black queens and n white queens into the chessboard, so that any two black queens are not on the same line, column or diagonal, and any two white queens are not on the same line, column or diagonal. How many ways are there in total? N is less than or equal to 8.
Input format
The first line of input is an integer n, representing the size of the chessboard.
Next N lines, each line has n integers of 0 or 1. If an integer is 1, it means that the corresponding position can be put to the queen. If an integer is 0, it means that the corresponding position cannot be put to the queen.
Output format
Output an integer indicating the total number of playback methods.
sample input
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
sample output
2
sample input
4
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
sample output
0

The solution ideas and codes are detailed in the following article:
Blue Bridge Cup 2n Queen's question


Time assistant

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Given the current time, please read it in English.
Time is expressed in hours and minutes. In English, the way to read a time is as follows:
If m is 0, read the hour, and then add "o'clock", for example, 3:00 reads "three o'clock".
If m is not 0, read out the hour, and then read out the minute. For example, 5:30 reads "five thirty".
The reading method of hour and minute uses the reading method of English number, in which 0-20 is read as:
  0:zero, 1: one, 2:two, 3:three, 4:four, 5:five, 6:six, 7:seven, 8:eight, 9:nine, 10:ten, 11:eleven, 12:twelve, 13:thirteen, 14:fourteen, 15:fifteen, 16:sixteen, 17:seventeen, 18:eighteen, 19:nineteen, 20:twenty.
30 for thirty, 40 for ty, 50 for fifty.
For numbers greater than 20 but less than 60, read the whole ten first, and then add the number of digits. For example, read "thirty one" first and then add "one".
According to the above rule, 21:54 reads "two one five four", 9:07 reads "nine seven", and 0:15 reads "Zero Five".
Input format
The input contains two non negative integers h and m, representing the hour and minute of time. There is no leading 0 before a non-zero number. H is less than 24, M is less than 60.
Output format
Output time and time in English.
sample input
0 15
sample output
zero fifteen

The code is as follows:

import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int h = scanner.nextInt();
		int m = scanner.nextInt();
		if(m==0){
			System.out.println(transform(h)+" "+"o'clock");
		}else{
			System.out.println(transform(h)+" "+transform(m));
		}
	}
	static String transform(int n){
		switch (n) {
		case 0 : return "zero";
		case 1 : return "one";
		case 2 : return "two";
		case 3 : return "three";
		case 4 : return "four";
		case 5 : return "five";
		case 6 : return "six";
		case 7 : return "seven";
		case 8 : return "eight";
		case 9 : return "nine";
		case 10 : return "ten";
		case 11 : return "eleven";
		case 12 : return "twelve";
		case 13 : return "thirteen";
		case 14 : return "fourteen";
		case 15 : return "fifteen";
		case 16 : return "sixteen";
		case 17 : return "seventeen";
		case 18 : return "eighteen";
		case 19 : return "nineteen";
		case 20 : return "twenty";
		case 30 : return "thirty";
		case 40 : return "forty";
		case 50 : return "fifty";
		default:
			int shi = (n/10)*10; //Extract the tens and multiply by 10
			int ge = n%10;//Extract bits
			return transform(shi) + " " + transform(ge);
		}
	}
}

Recovery number

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Loop fetching is fetching along the edge of the matrix. If there are countless or have been fetched in the current direction, turn 90 degrees to the left. It starts at the top left corner of the matrix and goes down.
Input format
The first input row is two positive integers m, n, representing the rows and columns of the matrix. Next, m lines, n integers per line, represent the matrix.
Output format
The output has only one line and mn number in total, which is the result of the input matrix loop. Numbers are separated by a space. There should be no extra space at the end of the line.
sample input
3 3
1 2 3
4 5 6
7 8 9
sample output
1 4 7 8 9 6 3 2 5
sample input
3 2
1 2
3 4
5 6
sample output
1 3 5 6 4 2

The code is as follows:

 
import java.util.Scanner;
 
/**
 * @author Administrator 
 *         Loop fetching is fetching along the edge of the matrix. If there are countless or have been fetched in the current direction, turn 90 degrees to the left. It starts at the top left corner of the matrix and goes down. Input format
 *         The first input row is two positive integers m, n, representing the rows and columns of the matrix. Next, m lines, n integers per line, represent the matrix. Output format
 *         The output has only one line and mn number in total, which is the result of the input matrix loop. Numbers are separated by a space. There should be no extra space at the end of the line.
 */
public class Main {
 
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		int n = sc.nextInt();
		int[][] a = new int[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				a[i][j] = sc.nextInt();
 
			}
 
		}
		int tot = 0, x = -1, y = 0;
		while (tot < m * n) {
			while (x + 1 < m && a[x + 1][y] != -1) {
				System.out.print(a[++x][y]+" ");
				a[x][y] = -1;
				++tot;
			}
			while (y + 1 < n && a[x][y + 1] != -1) {
				System.out.print(a[x][++y]+" ");
				a[x][y] = -1;
				++tot;
			}
			while (x - 1 >= 0 && a[x - 1][y] != -1) {
				System.out.print(a[--x][y]+" ");
				a[x][y] = -1;
				++tot;
			}
 
			while (y - 1 >= 0 && a[x][y - 1] != -1) {
				System.out.print(a[x][--y]+" ");
				a[x][y] = -1;
				++tot;
			}
		}
	}
 
}

Prediction of tortoise and hare race

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
There are all kinds of rabbits and tortoises in the world, but research has found that all rabbits and tortoises have a common feature - like running. Therefore, tortoise and hare competitions are taking place in every corner of the world. Xiaohua is very interested in this, so he decides to study the races between different rabbits and tortoises. He found that although rabbits run faster than tortoises, they have a well-known problem - Pride and laziness. So in the competition with tortoises, once the rabbits find that they are ahead of t meters or more at the end of any second, they will stop and rest for s seconds. For different rabbits, the values of t and s are different, but all tortoises are the same - they never stop until they reach the end.
However, some races are quite long and it will take a lot of time to watch the whole race. Xiaohua found that as long as he recorded the data of rabbits and tortoises after the start of each race - the speed of rabbits v1 (which means that rabbits can run v1 meters per second), the speed of tortoises v2, and the corresponding T, s values of rabbits, and the length of the track l - he could predict the results of the race. But Xiaohua is lazy and doesn't want to guess the result of the match by hand. So he found you, a talented student in the computer department of Tsinghua University, and asked for help. Please write a program to predict the result of the match for the entered data v1, v2, t, s, l.
Input format
The input has only one line, including five positive integers v1,v2, t, s, l separated by spaces, where (v1,v2 < = 100; T < = 300; s < = 10; l < = 10000 and the common multiple of v1,v2)
Output format
The output consists of two lines. The first line outputs the result of the match - a capital letter "T" or "R" or "D", indicating that the tortoise wins, the rabbit wins, or both reach the end at the same time.
The second line outputs a positive integer indicating the time (in seconds) it takes the winner (or both parties) to reach the destination.
sample input
10 5 5 2 20
sample output
D
4
sample input
10 5 5 1 20
sample output
R
3
sample input
10 5 5 3 20
sample output
T
4

The code is as follows:

import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int v1 = scanner.nextInt();
		int v2 = scanner.nextInt();
		int t = scanner.nextInt();//More than t meters
		int s = scanner.nextInt();//Waiting for s seconds
		int l = scanner.nextInt();
		int l1 = v1*1;//The rabbit has walked the distance
		int l2 = v2*1;//The journey the tortoise has completed
		int count = 0;
		int i = 0; //Used to indicate the passage of time
		for(i=2; l1<l&&l2<l; i++){//From the second second
			if(l1-l2>=t){//Rabbit over tortoise
				l1 = l1 - v1*s;
			}
			l1 = l1 + v1;//Plus one second of travel
			l2 = l2 + v2;//Plus one second of travel
		}
		if(l1>l2) System.out.println("R");//Rabbit wins
		if(l1<l2) System.out.println("T");//Turtle wins
		if(l1==l2) System.out.println("D");//It ends in a draw
		System.out.println(i-1);
	}
}

Chip test

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
There are n (2 ≤ n ≤ 20) chips, good and bad. It is known that there are more good chips than bad ones.
Each chip can be used to test other chips. When other chips are tested with a good chip, it can correctly give whether the chip under test is good or bad. When testing other chips with bad chips, good or bad test results will be given randomly (that is, this result has nothing to do with the actual quality of the chip being tested).
Give the test results of all chips and ask which chips are good ones.
Input format
The first line of input data is an integer n, indicating the number of chips.
The second row to the n+1 row is a table of n*n, with N data in each row. Each data i n the table is 0 or 1. The data in row I and column J (1 ≤ i, j ≤ n) in row n represents the test results obtained when the j-th chip is tested with the i-th chip. 1 represents good, 0 represents bad, and i=j is all 1 (does not mean the test results of the chip itself). The chip cannot test itself).
Output format
Output the numbers of all good chips in the order of small to large
sample input
3
1 0 1
0 1 0
1 0 1
sample output
1 3

The code is as follows:

import java.util.*;
/**
 * If the sum of each column and row is more than half, it means a good chip
 * Just having more than half of the sum of rows or columns doesn't make a good chip
 * Because there are more good chips than bad ones; if the chip being tested is a good chip
 * Then its test result must be more than 1:0. If the chip under test is a bad chip
 * Then his test result must be 0 to 1.
 * @author Administrator
 *
 */
public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[][] arr = new int[n][n];
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				arr[i][j] = scanner.nextInt();
			}
		}
		for(int i=0; i<n; i++){
			int rowsum = 0;
			int colsum = 0;
			for(int j=0; j<n; j++){
				rowsum += arr[i][j];
				colsum += arr[j][i];
			}
			if(rowsum>n/2 && colsum>n/2)
				System.out.print(i+1+" ");
		}
	}
}


FJ's string

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
FJ writes the following strings on the sandbox:
  A1 = "A"
  A2 = "ABA"
  A3 = "ABACABA"
  A4 = "ABACABADABACABA"
  ... ...
Can you find out the rules and write all the series AN?
Input format
Only one number: N ≤ 26.
Output format
Please output the corresponding string AN, ending with a line break. The output must not contain extra spaces or line breaks or carriage returns.
sample input
3
sample output
ABACABA

The code is as follows:

import java.util.Scanner;

/**
 * The rule is that the nth string is equal to (n-1) string + the nth letter + (n-1) string
 * @author Administrator
 *
 */
public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		System.out.println(str(n));
	}

	private static String str(int n) {
		if(n==1){
			return "A";
		}
		char c = (char) ('A'+(n-1));
		return str(n-1) + c + str(n-1);
	}
}


Dance of Sine

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Recently, FJ has set up a mathematical analysis course for his cows. FJ knows that if he wants to learn this course well, he must have a good basic skill of trigonometric function. So he is going to play a game of "dance of Sine" with the cows to improve their computing power.
We might as well set
  An=sin(1–sin(2+sin(3–sin(4+...sin(n))...)
  Sn=(...(A1+n)A2+n-1)A3+...+2)An+1
FJ wants the cows to calculate the value of Sn. Please help FJ print out the complete expression of SN to facilitate the cows to do the problem.
Input format
Only one number: n < 201.
Output format
Please output the corresponding expression Sn, ending with a line break. The output must not contain extra spaces or line breaks or carriage returns.
sample input
3
sample output
((sin(1)+3)sin(1–sin(2))+2)sin(1–sin(2+sin(3)))+1

The code is as follows:

import java.util.Scanner;
public class Main {
    static char flag = '-';	//Sign stored in An
    static int index = 0;	//Control the recursion times of An function
    static int index2;		//Control the number of recursion to find Sn function
    public static void getAn(int n) {	//Get An function
        index += 1;
        System.out.print("sin(");
        System.out.print(index);
        if(1 == index%2) {
            flag = '-';
        } else {
            flag = '+';
        }
        if(index < n) {		//Continue recursion when index is less than n
            System.out.print(flag);
            getAn(n);
        }
        System.out.print(")");
    }
    public static void getSn(int n) {
        if(n > 1) {
            System.out.print("(");
            getSn(n-1);
            System.out.print(")");
            index2 -= 1;
        }
        index = 0;		//Remember to reset the index to 0 every time you call the getAn() function
        getAn(n);		//print An
        //System.out.print("A"+n);
        System.out.print("+"+index2);
    }
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);
        int num = reader.nextInt();
        index2 = num;
        //getAn(num);
        getSn(num);
    }
}

Reading of numbers

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Professor Tom is teaching a course about genes to postgraduates. One thing bothers him a lot: there are thousands of base pairs on a chromosome, they number from zero to millions, tens of millions, even hundreds of millions.
For example, it's difficult to read the numbers accurately when explaining the bases at position 1234567009 to students.
Therefore, he urgently needs a system, and when he inputs 1234567009, he will give the corresponding reading method:
One billion two hundred and thirty-four million five hundred and sixty-seven thousand nine
In Chinese Pinyin
  shi er yi san qian si bai wu shi liu wan qi qian ling jiu
So he just needs to read.
Your task is to help him design such a system: given an Arabic numeral string, you can help him convert it into a Chinese Pinyin string according to the Chinese reading and writing specifications, and the two adjacent syllables are separated by a space character.
Note that it must be strictly in accordance with the specification, for example, "10010" is read as "Yi Wan Lin Shi" instead of "Yi Wan Lin Shi", "100000" is read as "shi wan" instead of "yi shi wan", "2000" is read as "er qian" instead of "liang qian".
Input format
There is a number string with a value size of no more than 2000000000.
Output format
Is a string of lowercase letters, commas, and spaces, representing the English reading of the number.
sample input
1234567009
sample output
shi er yi san qian si bai wu shi liu wan qi qian ling jiu

The code is as follows:

import java.util.Scanner;

/**
 * It can be found by observation that every four digits can be regarded as a unit, and their reading rules are the same. Then add "ten thousand" and "hundred million" in the middle. For example: 1234: one thousand two hundred and thirty-one;
12345678: Twelve million three hundred fifteen thousand six hundred seventy-eight;
123412345678:Twelve, three, four, twelve, three, four, five, six, seventy-eight;
ps.It is required that the number in the question should not exceed 2 billion.

Therefore, the detailed solving steps of this question are:
①Write a function f1(), which can read a four digit number.
②Write a function split(), which can divide a string of numbers into several four digits.
③Write a function f2(), which can read a string of numbers with f1() and split() functions.
④Write a function deal() to deal with illegal reading, for example, "0741" will read "0741";
"7041"Can read as "7401", "7401" can read as "7411", "7410" can read as "74110", etc.; and double zero problem.
 * @author Administrator
 *
 */
public class Main {
	static String[] du = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
	static String deal(String s){//Dealing with illegal reading
			s=s.replace("ling wan", "wan");
			s=s.replace("ling bai", "ling");
			s=s.replace("ling shi", "ling");
			s=s.replace("ling ling", "ling");
			if(s.endsWith(" ling")) //Zero at the end not read
				s=s.substring(0,s.length()-5);
			if(s.startsWith("yi shi")) //The first 10 doesn't read "ten" but "ten"
				s = s.replace("yi shi", "shi");
			if(s.endsWith("  wan ")) //Avoid reading "Yi Wan" as 100000000;
			    s = s.replace("  wan ", "");
		return s;
	}
	static String[] split(String s){//Divide a string of numbers from the back to the front into four digits. For example, 123456789 will be divided into: 12345 6789
		 int t = (int)Math.ceil((double)s.length()/4);//Rounding up 
		 String[] res = new String [t];
		 for(int i=t-1;i>0;i--){
			 res[i]= s.substring(s.length()-4,s.length());
			 s=s.substring(0,s.length()-4);
		 }
		 res[0] = s;
		 return res;
	}
	static String f1(String s){//Read a four digit number
		String fristZero=""; 
		while(s.startsWith("0")){  //If the beginning is zero
			s=s.substring(1,s.length());
			fristZero="ling ";
		}
		String res="";
		if(s.length()==1)
			res = fristZero + du[s.charAt(0)-48];
		else if (s.length()==2)
			res = fristZero + du[s.charAt(0)-48]+" shi "+du[s.charAt(1)-48];
		else if (s.length()==3)
			res = fristZero + du[s.charAt(0)-48]+" bai "+du[s.charAt(1)-48]+" shi "+du[s.charAt(2)-48];
		else if (s.length()==4)
			res = fristZero + du[s.charAt(0)-48]+" qian "+du[s.charAt(1)-48]+" bai "+du[s.charAt(2)-48]+" shi "+du[s.charAt(3)-48];
		return deal(res);
	}
	static String f2(String[] s){ //Read a string of numbers
		if(s.length == 1)
			return f1(s[0]);
		else if(s.length == 2)
			return f1(s[0]) + " wan " + f1(s[1]);
		else if(s.length == 3)
			return f1(s[0]) + " yi " + f1(s[1]) + " wan " + f1(s[2]);
		return "error!";
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		String res = f2(split(s));
		System.out.println(deal(res)); //In the end, we'll get rid of all illegal reading methods
	}
}

The price of perfection

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Palindrome string is a special string, which is read from left to right and right to left. Bruce Lee thinks the palindrome string is perfect. Now I will give you a string, which is not necessarily palindrome. Please calculate the minimum number of exchanges to make the string a perfect palindrome string.
Exchange is defined as the exchange of two adjacent characters
For example, mamad
First exchange ad: mamda
Second exchange MD: madma
The third exchange Ma: Madam (palindrome! Perfect! )
Input format
The first line is an integer N, representing the length of the next string (N < = 8000)
The second line is a string of length N. It contains only lowercase letters
Output format
If possible, output the minimum number of exchanges.
Otherwise, output Impossible
sample input
5
mamad
sample output
3

The code is as follows:

import java.util.Scanner;
/**
 * First of all, it's impossible: ① the length of the string is even, and some characters with odd occurrence times appear in the string
②The length of the string is odd, and more than one character with odd occurrence times appears in the string
 The solutions are as follows:
①Set the boundary front,end.
②Look for the same character from the back to the front.
③If it is found, move the character to the end (because the title stipulates that only two adjacent characters can be moved, so this refers to moving one by one until the target character is moved to the end), calculate the number of moves, and then narrow the boundary: front++;end -;
If it is not found, judge whether it is "Impossible". If not, output "Impossible" and end the program. If not, calculate the number of times required to move this character to the middle position (only the number of times, not the real move), and then reduce the boundary: front + +;
④Repeat steps ① to ③ until front > = end
⑤Output result
 * @author Administrator
 *
 */
class Main{
    static char[] swap(char[] chars,int f,int e){//Swap characters at f to e
        char t=chars[f];
        for(int i=f;i<e;i++){
            chars[i]=chars[i+1];
        }
        chars[e]=t;
        return chars;
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int N = sc.nextInt();
        String s=sc.next();
        char[] chars = new char[N];
        for(int i=0;i<N;i++){
            chars[i] = s.charAt(i);
        }

        int front=0,end=N-1,times=0;
        boolean oddNum = false;
        while(front < end){
            for(int i = end;i>=front;i--){
                if(i == front){//If the same character is not found at the front, that is, a character with an odd number of occurrences at the front
                    if(N%2==0 || oddNum){
                        System.out.println("Impossible");
                        System.exit(0);
                    }else{
                        times += (N/2)-front;
                        oddNum=true;
                        front++;
                        break;
                    }
                }
                if(chars[i] == chars[front]){//If found, swap
                    chars = swap(chars,i,end);
                    times += end-i;
                    front++;end--;
                    break;
                }
            }
        }
        System.out.println(times);
    }
}


Rectangle area intersection

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
There are two rectangles on the plane, whose sides are parallel to the X or Y axis of the rectangular coordinate system. For each rectangle, we give the coordinates of a pair of relative vertices. Please program to calculate the intersection area of two rectangles.
Input format
The input contains only two lines, each describing a rectangle.
In each row, the coordinates of a pair of relative vertices of the rectangle are given. The coordinates of each point are represented by two real numbers with absolute values no more than 10 ^ 7.
Output format
The output contains only one real number, which is the intersecting area and is reserved to two decimal places.
sample input
1 1 3 3
2 2 4 4
sample output
1.00

The code is as follows:

import java.text.DecimalFormat;
import java.util.Scanner;
/**
 * According to the meaning of the topic, the overlapped part of two rectangles must also be a rectangle;
 * And each edge is parallel to the X or Y axis. In this way, the four sides can be represented by X and Y separately.
 * So we can get the position of the four sides of the overlap rectangle according to the coordinates of the four points.
 * Then judge whether two rectangles intersect according to the position of four sides.
 * The left side is smaller than the right side, and the bottom side is smaller than the top side to represent the intersection.
 *
 */
public class Main {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		double x1 = in.nextDouble();
		double y1 = in.nextDouble();
		double x2 = in.nextDouble();
		double y2 = in.nextDouble();
		double x3 = in.nextDouble();
		double y3 = in.nextDouble();
		double x4 = in.nextDouble();
		double y4 = in.nextDouble();	
		double xl,yd,xr,yu;
		xl=Math.max(Math.min(x1, x2), Math.min(x3, x4));  //Left border abscissa
		yd=Math.max(Math.min(y1, y2), Math.min(y3, y4));  //Lower boundary ordinate
		xr=Math.min(Math.max(x1, x2), Math.max(x3, x4));  //Right border abscissa
		yu=Math.min(Math.max(y1, y2), Math.max(y3, y4));  //Vertical coordinate of upper boundary
		DecimalFormat d1 = new DecimalFormat("0.00");  //Output in 0.00 format
		if((xl<xr&&yd<yu))//If the left boundary is to the left of the right boundary and the lower boundary is to the bottom of the upper boundary, the rectangles intersect   
			System.out.println(d1.format((xr-xl)*(yu-yd)));	
		else   
			System.out.println(d1.format(0.00));
	}	
}

Matrix multiplication

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Given a matrix A of order N, the m power of output a (M is a non negative integer)
For example:
  A =
  1 2
  3 4
Power 2 of A
  7 10
  15 22
Input format
The first line is a positive integer N, M (1 < = N < = 30, 0 < = M < = 5), representing the order of matrix A and the required power
Next N lines, n non negative integers with absolute value no more than 10 in each line, describe the value of matrix A
Output format
Output a total of N lines, n integers in each line, representing the matrix corresponding to the M power of A. Separate adjacent numbers with a space
sample input
2 2
1 2
3 4
sample output
7 10
15 22

import java.util.*;

public class Main {
	static int n = 0; //global variable
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		n = scanner.nextInt();
		int m = scanner.nextInt();
		int[][] arr1 = new  int[n][n];
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				arr1[i][j] = scanner.nextInt();
			}
		}
		int[][] arr2 = arr1;
		if(m==0){//Zero power
			for(int i=0; i<n; i++){
				for(int j=0; j<n; j++){
					if(i==j)arr1[i][j] = 1;
					else arr1[i][j] = 0;
				}
			}
			print(arr1);
			System.exit(0);
		}
		for(int k=1; k<m; k++){
			int[][] t = new  int[n][n];
			for(int i=0; i<n; i++){
				for(int j=0; j<n; j++){
					t[i][j] = rowcol(arr1, arr2, i, j);
				}
			}
			arr1 = t;
		}
		print(arr1);
	}

	private static void print(int[][] arr1) {
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				System.out.print(arr1[i][j]+" ");
			}
			System.out.println();
		}
	}

	//Return to the sum of row and column multiplication
	private static int rowcol(int[][] arr1, int[][] arr2, int row, int col) {
		int res = 0;
		for(int i=0; i<n; i++){
			res += arr1[row][i]*arr2[i][col];
		}
		return res;
	}
}


Decomposing quality factor

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
The prime factorization of all integers in the interval [a,b] is obtained.
Input format
Enter two integers a, b.
Output format
Each line outputs a decomposition of the number, in the form of k=a1a2a3 (a1<=a2<=a3… , K is also from small to large (see the example for details)
sample input
3 10
sample output
3=3
4=22
5=5
6=23
7=7
8=222
9=33
10=25
Tips
First sift out all prime numbers, then decompose them.
Data size and engagement
  2<=a<=b<=10000

The code is as follows:

import java.util.Scanner;
import java.math.*;

/** 
*  A prime number is a prime number; a composite number is a number that is not a prime number.
*  Each composite number can be written in the form of multiplication of several prime numbers, which are called the prime factors of this composite number.
*  If a prime number is a divisor of a number, then the prime number is the prime factor of the number.
*  
*/
public class Main {
       public static void main(String[] args) {
              Scanner cin = new Scanner(System.in);
              int a = cin.nextInt();
              int b = cin.nextInt();
              for(int i = a; i < b+1; i++) {
                     System.out.print(i+"=");
                     int temp = i;                    
                     for(int j = 2; j <= temp; j++) {
                    	 //Judge whether this number is prime
                    	 while(temp% j == 0 && temp!=j) { //Core part
                             temp/=  j;
                             System.out.print(j+"*");
                          }
                    	 if(temp== j) {
                             System.out.print(j);
                             break;
                          }
                     }
                     System.out.println();
              }
       }
}

String comparison

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Given two strings of only uppercase or lowercase letters (between 1 and 10 in length), the relationship between them is one of the following 4 cases:
1: the two strings are not the same length. For example, Beijing and Hebei
2: the two strings are not only the same length, but also the characters in the corresponding positions are exactly the same (case sensitive), such as Beijing and Beijing
3: the length of two strings is equal, and the characters in corresponding positions can be completely consistent only without case sensitivity (that is to say, it does not satisfy case 2). For example, BEIjing and BEIjing
4: two strings are the same length, but even case insensitive cannot make them consistent. For example, Beijing and Nanjing
Programming determines which of the four categories the relationship between the two input strings belongs to, and gives the number of the category.
Input format
Contains two lines, each of which is a string
Output format
There is only one number indicating the relationship number of the two strings
sample input
BEIjing
beiJing
sample output
3

The code is as follows:

import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		String str1 = scanner.next();
		String str2 = scanner.next();
		if(str1.length()!=str2.length()){//Different length
			System.out.println(1);
			System.exit(0);
		}
		if(str1.equals(str2)){//Exactly the same
			System.out.println(2);
			System.exit(0);
		}
		if(f3(str1, str2)){//Case insensitive
			System.out.println(3);
			System.exit(0);
		}
		if(f3(str1, str2)==false){//Case insensitive
			System.out.println(4);
			System.exit(0);
		}
	}

	//Used to determine whether it is the same without case sensitivity
	private static boolean f3(String str1, String str2) {
		str1 = str1.toLowerCase();
		str2 = str2.toLowerCase();
		return str1.equals(str2);
	}
}

Time conversion

Resource constraints
Time limit: 1.0s memory limit: 512.0MB
Problem description
Given a time t in seconds, it is required to use the format of "< H >: < m >: < s >". <H> Represents time, < m > represents minute, and < s > represents second. They are all integers and have no leading "0". For example, "0:0:0" should be output if t=0, and "1:1:1" if t=3661.
Input format
The input has only one line and is an integer t (0 < = T < = 86399).
Output format
The output has only one line, which is the time in the format of "< H >: < m >: < s >", excluding quotation marks.
sample input
0
sample output
0:0:0
sample input
5436
sample output
1:30:36

The code is as follows:

import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		int t = scanner.nextInt();
		int s = t%60; //second
		int m = (t/60)%60; //branch
		int h = t/3600; //Time
		System.out.println(h + ":" + m + ":" + s);
	}
}

59 original articles published, 7 praised, 2696 visited
Private letter follow

Tags: Java less REST Programming

Posted on Tue, 10 Mar 2020 00:30:09 -0400 by VenusJ