Algorithmic Solutions and Analysis for the 2020 Blue Bridge Cup Java Provincial Exam
Problem A: Door Plaque Counting
Objective: Determine the total count of the digit '2' required to generate serial numbers from 1 to 2020.
Analysis: Iterate through every integer in the range [1, 2020]. For each number, extract individual digits or convert to a string representation to check if the character '2' is present. Accumulate the count whenever a match is found.
Implementation:
public class DoorPlaqueCount {
public static void main(String[] args) {
int occurrence = 0;
for (int i = 1; i <= 2020; i++) {
String sequence = Integer.toString(i);
for (char c : sequence.toCharArray()) {
if (c == '2') {
occurrence++;
}
}
}
System.out.println(occurrence);
}
}
Problem B: Finding Subsequence "2020"
Status: Challenge Unresolved in this context. Requires identifying the frequency of the subsequence "2020" within a provided grid of digits. The problem involves combinatorial counting logic which was not fully implemented here.
Problem C: Snake-like Number Matrix
Score: Full Marks (10/10)
Pattern Recognition: Observing the snake pattern reveals that diagonal elements share specific differences. By calculating the values at coordinates (i, i) and (i+1, i+1), a recurrence relation can be esatblished to determine the center value without simulating the entire grid.
Problem D: Seven-Segment Display
Result: 80 distinct shapes can be formed using 7-segment displays by turning on various combinations of segments.
Methodology: Depth-First Search (DFS) combined with graph connectivity checks ensures valid digit formations are counted while avoiding duplicates.
Problem E: String Sorting Operations
Target Sequence: jonmlkihgfedcba
Logic: To achieve maximum swap counts for bubble sort on a string of length 15, reverse order is optimal. Moving the 6th character to the front modifies the inversion count significantly.
Swap Counter Logic:
public static int calculateInversions(String text) {
char[] buffer = text.toCharArray();
int swaps = 0;
int len = buffer.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (buffer[j] > buffer[j + 1]) {
char temp = buffer[j];
buffer[j] = buffer[j + 1];
buffer[j + 1] = temp;
swaps++;
}
}
}
return swaps;
}
Problem F: Score Statistics Analysis
Requirements: Calculate maximum score, minimum score, and average score from n student inputs. Output must format the average to two decimal places.
Optimization: Instead of sorting the array first, track min, max, and sum during the input phase to reduce time complexity to O(N).
import java.util.Scanner;
public class ExamStatistics {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
if (!reader.hasNextInt()) return;
int count = reader.nextInt();
int maxGrade = 0;
int minGrade = 100;
long totalPoints = 0;
for (int i = 0; i < count; i++) {
int score = reader.nextInt();
if (score > maxGrade) maxGrade = score;
if (score < minGrade) minGrade = score;
totalPoints += score;
}
System.out.println(maxGrade);
System.out.println(minGrade);
System.out.printf("%.2f\n", (double) totalPoints / count);
}
}
Problem G: Frequency Character Analsyis
Description: Given a string of lowercase English letters, find the character with the highest frequency. In case of a tie, select the one appearing earliest alphabetically.
Approach: Use an integer array of size 26 to store frequencies indexed by character offset. Iterate once to populate counts, then iterate the count array to find the maximum index.
import java.util.Scanner;
public class WordFrequencyAnalyzer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.next();
int[] frequencyMap = new int[26];
for (int k = 0; k < word.length(); k++) {
int idx = word.charAt(k) - 'a';
frequencyMap[idx]++;
}
int maxFreq = 0;
int bestCharIndex = -1;
for (int m = 0; m < frequencyMap.length; m++) {
if (frequencyMap[m] > maxFreq) {
maxFreq = frequencyMap[m];
bestCharIndex = m;
}
}
System.out.println((char) ('a' + bestCharIndex));
System.out.println(maxFreq);
}
}
Problem H: Digital Triangle Path Sum
Sample Input:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Output: 27
Solution Strategy: Dynamic Programming. Transform the triangle such that each element holds the maximum path sum from the top to that position. The base cases involve boundary checks.
import java.util.Scanner;
public class TriangleMaxPath {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rows = in.nextInt();
int[][] dp = new int[rows][rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c <= r; c++) {
dp[r][c] = in.nextInt();
}
}
for (int r = 1; r < rows; r++) {
for (int c = 0; c <= r; c++) {
int leftParent = (c > 0) ? dp[r - 1][c - 1] : 0;
int rightParent = (c < r) ? dp[r - 1][c] : 0;
// Handle boundaries specifically for triangle shape
int prevMax = 0;
if (c == 0) prevMax = dp[r-1][0];
else if (c == r) prevMax = dp[r-1][r-1];
else prevMax = Math.max(dp[r-1][c-1], dp[r-1][c]);
dp[r][c] += prevMax;
}
}
int mid = rows % 2 == 0 ? rows / 2 : rows / 2 + 1;
if (rows % 2 == 0) {
System.out.println(Math.max(dp[rows - 1][mid - 1], dp[rows - 1][mid]));
} else {
System.out.println(dp[rows - 1][mid - 1]);
}
}
}
Problem I: Substring Diversity Sum
Problem Definition: Calculate the sum of unique character counts for all possible non-empty substrings of a given string S.
Naive Approach: Generate all substrings and utilize a Set to count distinct characters for each substring. This approach yields partial points for smaller constraints due to high time complexity.
Code Structure:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class SubstringFenValue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
long totalVal = 0;
for (int start = 0; start < s.length(); start++) {
for (int end = start; end < s.length(); end++) {
String sub = s.substring(start, end + 1);
totalVal += countDistinct(sub);
}
}
System.out.println(totalVal);
}
private static int countDistinct(String str) {
Set<Character> seen = new HashSet<>();
for (char ch : str.toCharArray()) {
seen.add(ch);
}
return seen.size();
}
}
Problem J: Decorative Bead Placement
Status: Implementation Pending. This problem typically involves combinatorial optimization or dynamic programming strategies which require deeper constraint analysis beyond standard brute force methods.