QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#874334#3445. Numbers On a Treefernandes_queilaML 101ms44740kbJava172.1kb2025-01-28 01:49:402025-01-28 01:49:41

Judging History

你现在查看的是最新测评结果

  • [2025-01-28 01:49:41]
  • 评测
  • 测评结果:ML
  • 用时:101ms
  • 内存:44740kb
  • [2025-01-28 01:49:40]
  • 提交

answer

import java.util.Scanner;
import java.util.HashMap;

public class BinarySearchTree {

    public static int binarySearch(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static int calculateLabel(int height, String path) {
        int totalNodes = (int) Math.pow(2, height + 1) - 1;
        int label = totalNodes;
        int index = 0;

        HashMap<String, Integer> memoization = new HashMap<>();

        for (int i = 0; i < path.length(); i++) {
            char move = path.charAt(i);
            String key = index + "-" + move; 

            if (memoization.containsKey(key)) {
                index = memoization.get(key);
            } else {
                if (Character.toLowerCase(move) == 'l') {
                    index = 2 * index + 1;
                } else if (Character.toLowerCase(move) == 'r') {
                    index = 2 * index + 2;
                } else {
                    throw new IllegalArgumentException("Invalid move: use 'L' or 'R'.");
                }
                memoization.put(key, index);
            }
        }

        label -= index;

        int[] nodes = new int[totalNodes];
        for (int i = 0; i < totalNodes; i++) {
            nodes[i] = i;
        }

        int searchResult = binarySearch(nodes, label);
        return (searchResult != -1) ? searchResult : label;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String inputLine = scanner.nextLine().strip();
        String[] parts = inputLine.split(" ");

        int height = Integer.parseInt(parts[0]);
        String path = parts.length > 1 ? parts[1] : "";

        int result = calculateLabel(height, path);
        System.out.println(result);

        scanner.close();
    }
}

詳細信息

Test #1:

score: 100
Accepted
time: 93ms
memory: 44740kb

input:

3 LR

output:

11

result:

ok single line: '11'

Test #2:

score: 0
Accepted
time: 101ms
memory: 44464kb

input:

3 RRL

output:

2

result:

ok single line: '2'

Test #3:

score: 0
Accepted
time: 78ms
memory: 44112kb

input:

2

output:

7

result:

ok single line: '7'

Test #4:

score: 0
Accepted
time: 99ms
memory: 44260kb

input:

3 LRL

output:

6

result:

ok single line: '6'

Test #5:

score: -100
Memory Limit Exceeded

input:

26 RRLLLLRRRL

output:


result: