66. Preparing for the Blue Bridge Cup - The 13th Mock Competition (Java Group)

Blue Bridge Cup: National Software and Information Technology Professional Talent Competition [1]   is a national IT discipline competition organized by the Talent Exchange Center of the Ministry of Industry and Information Technology. A total of more than 1,200 colleges and universities across the country, including Peking University, Tsinghua University, and Shanghai Jiaotong University, participated in the competition, and the cumulative number of participants exceeded 400,000. [2] 

In 2020, the Blue Bridge Cup Competition was included in the "National College Subject Competition Ranking List" issued by the China Higher Education Society. It is an important competition item for college education and teaching reform and innovative talent training. [3] 

Background: Preparation for the 13th Blue Bridge Cup Java Group Provincial Competition

Lanqiao Cup official website: https://dasai.lanqiao.cn/pages/dasai/index.html

content

answer requirements

Topic description

Topic 1

topic two

topic three

topic four

topic five

topic six

topic seven

topic eight

topic nine

topic ten

Summarize

Algorithm exercise


answer requirements

Topic description

Note: To answer the question, please click the "Submit this question" button at the top of the page, the page will jump to the page for submitting the code, select your compiled language, paste your written code into the code box, and then click "" Submit your answer".

After your answer is submitted to the system, the system will automatically score your code and jump to the list of results. You can directly see the status of the code you submitted from the list, usually after a few seconds. to the scoring result.

This question is the first question. The C++ and Java codes have been given in the prompt. You can directly copy this code and submit it as your own code.

Note in particular that Java's main class name must be Main.

Topic 1

Xiaolan's IP address is 192.168.*.21, where * is a number, what is the maximum possible number?

Answer: 255

Problem solution: It consists of 32-bit binary numbers. The IP address is a 4-byte binary number, which is divided into 4 segments, each segment is 8-bit binary numbers, for a total of 32-bit binary numbers. An IP address is divided into two parts, namely the network address and the host address. From the range of values, it can be judged that the maximum value is 255 (2^8-1=255), which is common sense.

topic two

If an integer g can divide integers A and B at the same time, then g is said to be the common divisor of A and B. For example: 43 is the common divisor of 86 and 2021.
How many numbers from 1 (inclusive) to 2021 (inclusive) have a common divisor greater than 1 with 2021.

Please note that 2021 and 2021 have a common divisor greater than 1, so you need to count one when calculating.

Answer: 89

Problem solution: The gcd function is a common divisor function in Java. It searches one by one from 1 to 2021. When its common divisor is greater than 1, that is, greater than or equal to 2, it means that it has a common divisor and counts

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int count = 0;
		for (int i = 1; i <= 2021; i++) {
			if (gcd(i, 2021) > 1) {
				count++;
			}
		}
		System.out.println(count);
	}

	static int gcd(int a, int b) {
		return b > 0 ? gcd(b, a % b) : a;
	}
}

topic three

2021 is a very special number that can be expressed as the squared difference of two non-negative integers, 2021 = 45 * 45 - 2 * 2.
2025 is also a special number, it can be represented as 2025 = 45 * 45 - 0 * 0. Excuse me, how many such numbers are there in 1 to 2021?
Note that some numbers have multiple representations, such as 9 = 3 * 3 - 0 * 0 = 5 * 5 - 4 * 4, which is counted only once for the answer.

Answer: 1516

Problem solution: Iterative loop through nested loops to achieve the purpose of full matching, which involves a mathematical problem, sum= a*a - b*b, that is, sum = (a+b)(ab), when sum is a positive number When b<a, b is the inner loop. Since the value of sum is (1 <= sum <= 2021), to get the minimum positive number, there is a+b=1 or ab=1, obviously ab= If 1 is established, then there is b=a-1, substitute the expression sum = (a+a-1)(a-a+1), then there is 2021 = 2a-1, a=1011, the condition is recorded as 1, count Statistics, so there is the following code:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int count = 0;
		int[] arr = new int[2022];
		for (int i = 1; i <= 1011; i++) {
			for (int j = 0; j < i; j++) {
				int sum = i * i - j * j;
				if (sum <= 2021) {
					arr[sum] = 1;
				}
			}
		}
		for (int j = 1; j <= 2021; j++) {
			if (arr[j] == 1)
				count++;
		}
		System.out.println(count);
	}
}

topic four

Xiaolan uses a string of 01 to express a piece of text. This text contains a, b, c, d, e, f and a total of 6 letters. The number of occurrences of each letter is: a appears 10 times, b appears 20 times, c occurs 3 times, d occurs 4 times, e occurs 18 times, and f occurs 50 times.

Xiaolan intends to use a certain 01 string to represent each letter, and the length of the 01 string for different letters can be different.
When representing text, the 01 string corresponding to each letter is directly connected to form the final 01 string. In order to restore the text normally, the code of Xiaolan must be a prefix code, that is, the 01 string corresponding to any character cannot be the prefix of the 01 string corresponding to another character.

For example, the following is a valid encoding:
 a: 000
 b: 111
 c: 01
 d: 001
 e: 110
 f: 100

The length of c is 2, and the encoding length of other letters is 3. In this way, the total length required for this text is: 103+203+32+43+183+503=312.
The above encoding is obviously not optimal. Changing the encoding of f above to 10 still satisfies the condition, but the total length is 262, which is 50 shorter.
In order to make the total length of the encoding as small as possible, the encoding corresponding to the characters with a large number of occurrences should be short, and the encoding corresponding to the characters with a small number of occurrences should be longer.
 Excuse me, in the optimal case, what is the minimum total length after encoding?

Answer: 219

Problem solution: Huffman coding, it is recommended to get to know them, leave two links here

Learn Huffman Coding in 13 Minutes

The most complete Huffman tree Huffman coding explanation, brother, you deserve it

topic five

The following matrix contains six characters of ABCDEF. How many times does the character appear the most?
 FFEEFEAAECFFBDBFBCDA
 DACDEEDCCFFAFADEFBBA
 FDCDDCDBFEFCEDDBFDBE
   EFCAAEECEECDCDECADDC
 DFAEACECFEADCBFECADF
 DFBAAADCFAFFCEADFDDA
 EAFAFFDEFECEDEEEDFBD
 BFDDFFBCFACECEDCAFAF
 EFAFCDBDCCBCCEADADAE
 BAFBACACBFCBABFDAFBE
   FCFDCFBCEDCEAFBCDBDD
 BDEFCAAAACCFFCBBAAEE
 CFEFCFDEEDCACDACECFF
 BAAAFACDBFFAEFFCCCDB
 FADDDBEBCBEEDDECFAFF
   CDEAFBCBBCBAEDFDBEBB
 BBABBFDECBCEFAABCBCF
 FBDBACCFFABEAEBEACBB
 DCBCCFADDCACFDEDECCC
 BFAFCBFECAACAFBCFBAF

Answer: 78

Solution: The efficiency of using HashMap for this problem will be very high. When it is judged that there is no character character at the beginning, set its mapping value to 1, and then add 1 to its value when it is judged to exist, loop through all characters, and finally get output corresponding to each key the value of

import java.util.HashMap;
import java.util.Map;

public class Main {
	static String chars = 
			"FFEEFEAAECFFBDBFBCDA" + 
			"DACDEEDCCFFAFADEFBBA" + 
			"FDCDDCDBFEFCEDDBFDBE" + 
			"EFCAAEECEECDCDECADDC" + 
			"DFAEACECFEADCBFECADF" + 
			"DFBAAADCFAFFCEADFDDA" + 
			"EAFAFFDEFECEDEEEDFBD" + 
			"BFDDFFBCFACECEDCAFAF" + 
			"EFAFCDBDCCBCCEADADAE" + 
			"BAFBACACBFCBABFDAFBE" + 
			"FCFDCFBCEDCEAFBCDBDD" + 
			"BDEFCAAAACCFFCBBAAEE" + 
			"CFEFCFDEEDCACDACECFF" + 
			"BAAAFACDBFFAEFFCCCDB" + 
			"FADDDBEBCBEEDDECFAFF" + 
			"CDEAFBCBBCBAEDFDBEBB" + 
			"BBABBFDECBCEFAABCBCF" + 
			"FBDBACCFFABEAEBEACBB" + 
			"DCBCCFADDCACFDEDECCC" + 
			"BFAFCBFECAACAFBCFBAF";
	
	public static void main(String[] args) {
		Map<Character, Integer> map = new HashMap<>();
		for(int i = 0; i < chars.length(); i++) {
			char ch = chars.charAt(i);
			if(ch == 'A' || ch == 'B' || ch == 'C' || ch == 'D' || ch == 'E' || ch == 'F') {
				if(!map.containsKey(ch)) {
					map.put(ch, 1);
				} else {
					map.put(ch, map.get(ch) + 1);
				}
			}
		}
		System.out.println(map.get('A'));
		System.out.println(map.get('B'));
		System.out.println(map.get('C'));
		System.out.println(map.get('D'));
		System.out.println(map.get('E'));
		System.out.println(map.get('F'));
	}
}

topic six

Problem Description

Xiaolan wants to go to the store to buy pencils.
Pencils must be bought in a box of 12, and the price is p yuan.
Xiao Lan wants to buy at least t pencils. How much is the minimum cost?

input format

Input a line containing two integers p, t, separated by a space.

Output Format The output line contains an integer representing the answer.

sample input

5 30

Sample output

15

Sample description

Xiaolan has to buy at least 3 boxes to guarantee the purchase of 30 pencils, which costs a total of 15 yuan.

Evaluate use case size and conventions

For all evaluation cases, 1 <= p <= 100, 1 <= t <= 10000.

Solution: if less than 12, enter 1 directly

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int p = input.nextInt();
		int t = input.nextInt();
		int num = t / 12;
		int rem = t % 12;
		if (rem > 0) {
			num = num + 1;
		}
		System.out.println(num * p);
	}
}

topic seven

Problem Description

Given the lengths a, b, and c of the three sides of a triangle, ask whether the triangle is a right triangle.

input format

The input line contains three integers a, b, c, which represent the lengths of the three sides of the triangle, separated by a space between adjacent integers.

output format

If it is a right triangle, output "YES" (all caps), otherwise print "NO" (all caps).

sample input

3 4 5

Sample output

YES

sample input

4 5 4

Sample output

NO

Evaluate use case size and conventions

1 <= a, b, c <= 1000 for all evaluation cases.
 

Solution: The composition conditions of a triangle are: Among the three sides of the triangle, any side is greater than the difference between the other two sides, and any side is less than the sum of the other two sides.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int a = input.nextInt();
		int b = input.nextInt();
		int c = input.nextInt();
		if ((a + b > c || a + c > b || b + c > a) && (a - b < c || a - c < b || b - c < a)) {
			if (a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		} else {
			System.out.println("NO");
		}
	}
}

topic eight

Problem Description
n children are playing a game, each of whom wants to share a little secret of his own.
Each child has a number from 1 to n, and the numbers are not repeated.
To make the game more interesting, the teacher gave each child a card with a number from 1 to n, each of which appeared exactly once.
Each child writes his own secret on a piece of paper, and then passes the secret to the corresponding numbered child according to the number on the card issued by the teacher. If the number that the teacher sends him happens to be his own number, the secret remains in his own hands.
After the children get other people's secrets, they will write down the secrets, and the teacher will instruct all the children to continue to pass on the secrets in their hands, and still pass the secrets to the corresponding numbered children according to the numbers on the cards issued by the teacher.
This is repeated n times.
Now, every child has memorized a lot of secrets.
The teacher now wants to find some children who can tell all the secrets. How many children does the teacher want to find at least?
Input format
The first line of input contains an integer n.
The second line contains n integers a[1], a[2], …, a[n], and the adjacent integers are separated by spaces, representing the numbers received by the children numbered 1 to n respectively.
Output Format The
output line contains an integer representing the answer.
Example input
6
2 1 3 5 6 4
Example output
3
Example description
In the end, children 1 and 2 know each other's secrets, child 3 only knows their own secrets, and children 4, 5, and 6 know each other's secrets.
It takes at least 3 children to tell all the secrets.
Measurement case size and conventions
For 30% of the measurement cases, 2 <= n <= 30.
For 60% of the evaluation cases, 2 <= n <= 1000.
2 <= n <= 100000 for all evaluation cases.

Problem solution: Union search algorithm, just like a linked list, the contents of this linked list will be known by everyone in the linked list. In the final analysis, it is to search the chain. Here are two links.

Union search basics | rookie tutorial

And check the set to quickly find | rookie tutorial

import java.util.Scanner;

public class Main {
	static int n;
	static int[] a;
	static int num = 0;

	static int find(int k) {
		if (a[k] == k)
			return k;
		return a[k] = find(a[k]);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		n = input.nextInt();
		int[] friends = new int[n + 1];
		a = new int[n + 1];
		for (int i = 1; i <= n; i++) {
			a[i] = i;
			friends[i] = input.nextInt();			
		}
		for (int i = 1; i <= n; i++) {
			if (find(i) != find(friends[i]))
				a[find(i)] = find(friends[i]);
		}
		for (int i = 1; i <= n; i++) {
			if (a[i] == i)
				num++;
		}
		System.out.println(num);
	}
}

topic nine

Problem Description
A permutation of 1 to n is called a semi-increasing sequence, which means that the values ​​in the odd-numbered positions in the permutation increase monotonically, and the values ​​in the even-numbered positions also monotonically increase.
For example: (1, 2, 4, 3, 5, 7, 6, 8, 9) is a semi-increasing sequence because its odd positions are 1, 4, 5, 6, 9, monotonically increasing, even numbers The values ​​at the positions are 2, 3, 7, 8, also monotonically increasing.
Excuse me, how many semi-increasing sequences are there in the permutation 1 to n?
Input Format
The input line contains a positive integer n.
Output Format
The output line contains an integer representing the answer, the answer may be large, please output the remainder of dividing the answer by 1000000007.
Example Input
5
Example Output
10
Example Description
There are the following semi-increasing sequences:
 (1, 2, 3, 4, 5)
 (1, 2, 3, 5, 4)
 (1, 2, 4, 3, 5)
   (1, 3, 2, 4, 5)
 (1, 3, 2, 5, 4)
 (1, 4, 2, 5, 3)
 (2, 1, 3, 4, 5)
   (2, 1, 3 , 5, 4)
   (2, 1, 4, 3, 5)
   (3, 1, 4, 2, 5)
Evaluation case size and convention
For 50% of evaluation cases, 2 <= n <= 20.
2 <= n <= 1000 for all evaluation cases.

Problem solution: permutation and combination problem, assuming 100 numbers, 50 odd numbers are incremented, and the remaining 50 even numbers must be incremented and unique, because there are only 50 numbers left and they need to be incremented. Different parameters are passed in for even numbers and even numbers, and the remainder is taken. calculate

import java.util.Scanner;

public class Main {
	public static long group(long a, long b) {
		long ans = 1;
		int rem = (int) 1e9 + 7;
		for (long i = 1, j = a; i <= b; i++, j--) {
			ans = ans * (j / i) % rem;
		}
		return ans;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		long n = input.nextLong();
		if (n % 2 == 0) {
			System.out.println(group(n, n / 2));
		} else
			System.out.println(group(n, (n + 1) / 2));
	}

}

topic ten

Problem Description

  Xiao Lan lives in LQ City, and today he is going to Xiao Qiao's house to play. LQ city can be seen as a grid with n rows and m columns. Xiao Lan's family lives in row 1 and column 1, and Xiao Qiao's family lives in row n and column m. Xiaolan can walk inside the grid, but he doesn't want to go outside the grid. Some parts of the city are scenic parks, and others are bustling streets. Xiaolan likes parks, not streets. He marked each square in the grid with an attribute, either a favorite park, marked 1, or a disliked street, marked 2. The places where Xiao Lan and Xiao Qiao live are marked as 1. Little Blue can only go from one square to adjacent squares in the same row or column at a time. He wants to find a path so that he does not walk the street marked 2 twice in a row. How many times does he have to go through the street at least under this premise?
input format

  The first line of input contains two integers n, m, separated by a space. The next n lines, each with a length of m-th number string, represents the label of the city.

output format

A line of output contains an integer representing the answer. If there is no solution that meets the condition, output -1.

sample input

3 4 1121 1211 2211

Sample output

1

sample input

3 4 1122 1221 2211

Sample output

-1

sample input

5 6 112121 122221 221212 211122 111121

Sample output

5

Evaluate use case size and conventions

  For 50% of the evaluation cases, 2 <= n, m <= 20. 2 <= n, m <= 300 for all evaluation cases.

Answer: It seems that this question is not for me, there is no idea. Learn from the idea of ​​​​the great god dfs search again

reference:

Algorithmic Basics: An Intuitive Explanation of BFS and DFS

BFS and DFS Algorithms - Short Book

import java.util.Scanner;

public class Main {
    private static final int INF = 0x3f3f3f3f;
    private static int n, m, res = INF;
    private static int[][] map = new int[305][305];
    private static boolean[][] st = new boolean[305][305];

    private final static int[][] next = {
            {-1, 0}, {0, 1}, {1, 0}, {0, -1}
    };

    private static void dfs(int x, int y, int count) {  //count记录已经走过的街道的数量
        if(x == n - 1 && y == m - 1) {
            // 到终点了
            res = Math.min(res, count);
            return;
        }

        st[x][y] = true;
        for(int i = 0; i < 4; i++) {
            int tx = x + next[i][0];
            int ty = y + next[i][1];

            if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
            if(st[tx][ty]) continue;
            if(map[tx][ty] == 2 && map[x][y] == 2) continue;

            dfs(tx, ty, map[x][y] == 2 ? count + 1 : count);
        }
        st[x][y] = false;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();

        for(int i = 0; i < n; i++) {
            String line = sc.next();
            for(int j = 0; j < m; j++) {
                int ch = line.charAt(j);
                int cur = ch - '0';
                map[i][j] = cur;
            }
        }
        dfs(0, 0, 0);
        if(res == INF) res = -1;
        System.out.println(res);
    }
}


Summarize

Intuitive summary: There is still a fighting force in the first nine games of the simulation game, which generally requires some computer common sense, built-in functions in Java, violent solution of for, conversion of characters, strings, and shaping, some collection frameworks, and collection and arrangement. Combination problems, etc., review more and summarize more, I believe the provincial competition will not be difficult

Algorithm exercise

Fifty-nine, preparing for the Blue Bridge Cup - Java Algorithm (Basic Exercise 1 ) 1001.2014.3001.5501 60. Prepare for the Blue Bridge Cup - Java Algorithm (Basic Exercise 2) A national IT discipline competition organized by the Talent Exchange Center. A total of more than 1,200 colleges and universities across the country, including Peking University, Tsinghua University, and Shanghai Jiaotong University, participated in the competition, and the cumulative number of participants exceeded 400,000. [2] In 2020, the Blue Bridge Cup Competition was included in the "National Colleges and Universities Discipline Competition Ranking List" issued by the China Higher Education Association. It is an important competition item for college education and teaching reform and innovative talent training. [3] Background: The 13th Blue Bridge Cup Java Group Provincial Competition Preparation Catalog =1001.2014.3001.5501


A daily insight:

        All things push me to grow, there is no reason to stop

                                                                                                                                            --Thomas

Guess you like

Origin blog.csdn.net/m0_54925305/article/details/122715106