JAVA ACM算竞输入输出加速模板代码,附加容器使用

模板代码

import java.io.*;
import java.math.*;
import java.util.*;

// 实现Closeable接口以支持try-with-resources
class AReader implements Closeable {
    private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private StringTokenizer tokenizer = new StringTokenizer("");

    private String innerNextLine() {
        try {
            return reader.readLine();
        } catch (IOException ex) {
            return null;
        }
    }

    public boolean hasNext() {
        while (!tokenizer.hasMoreTokens()) {
            String nextLine = innerNextLine();
            if (nextLine == null) {
                return false;
            }
            tokenizer = new StringTokenizer(nextLine);
        }
        return true;
    }

    public String nextLine() {
        tokenizer = new StringTokenizer("");
        return innerNextLine();
    }

    public String next() {
        hasNext();
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }

    public float nextFloat() {
        return Float.parseFloat(next());
    }

    public BigInteger nextBigInt() {
        return new BigInteger(next());
    }

    public BigDecimal nextBigDecimal() {
        return new BigDecimal(next());
    }

    @Override
    public void close() throws IOException {
        if (reader != null) {
            reader.close();
        }
    }
}

class AWriter implements Closeable {
    private BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    // 添加额外的打印方法
    public void print(Object object) throws IOException {
        writer.write(object.toString());
    }
    
    public void print(char c) throws IOException {
        writer.write(c);
    }
    
    public void print(String s) throws IOException {
        writer.write(s);
    }
    
    public void print(int i) throws IOException {
        writer.write(Integer.toString(i));
    }
    
    public void print(long l) throws IOException {
        writer.write(Long.toString(l));
    }
    
    public void print(double d) throws IOException {
        writer.write(Double.toString(d));
    }
    
    public void print(float f) throws IOException {
        writer.write(Float.toString(f));
    }

    // 添加带换行的打印方法
    public void println() throws IOException {
        writer.newLine();
    }
    
    public void println(Object object) throws IOException {
        writer.write(object.toString());
        writer.newLine();
    }
    
    public void println(char c) throws IOException {
        writer.write(c);
        writer.newLine();
    }
    
    public void println(String s) throws IOException {
        writer.write(s);
        writer.newLine();
    }
    
    public void println(int i) throws IOException {
        writer.write(Integer.toString(i));
        writer.newLine();
    }
    
    public void println(long l) throws IOException {
        writer.write(Long.toString(l));
        writer.newLine();
    }
    
    public void println(double d) throws IOException {
        writer.write(Double.toString(d));
        writer.newLine();
    }
    
    public void println(float f) throws IOException {
        writer.write(Float.toString(f));
        writer.newLine();
    }

    // 格式化输出
    public void printf(String format, Object... args) throws IOException {
        writer.write(String.format(format, args));
    }

    // 手动刷新缓冲区
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        if (writer != null) {
            writer.close();
        }
    }
}

public class Main {
    static void solve(AReader in, AWriter out) throws Exception {
        
    }
    
    public static void main(String[] args) throws Exception {
        AReader in = new AReader();
        AWriter out = new AWriter();
        
        int t = 1;
        // t = in.nextInt();
        while (t -- > 0) {
            solve(in, out);
        }
        
        out.flush();
        in.close();
        out.close();
    }
}

使用示例:

public class Main {
    public static void main(String[] args) throws Exception {
        AReader in = new AReader();
        AWriter out = new AWriter();
        
        int a = in.nextInt();
        float b = in.nextFloat();
        double c = in.nextDouble();
        String d = in.next();
        String e = in.nextLine();
        long f = in.nextLong();
        char g = in.next().charAt(0);
        
        out.print(a);
        out.println(b);
        out.printf("%.2f\n", c);
        
        out.flush();
        in.close();
        out.close();
    }
}

动态数组,对应 C++ 的 vector

List<Integer> list = new ArrayList<>();
list.add(10);        // 添加元素
list.add(0, 5);      // 在索引0处插入元素(变成:[5, 10])
list.set(1, 20);     // 设置索引1处的元素为20(变成:[5, 20])
int num = list.get(0); // 获取索引0的元素(5)
list.remove(0);      // 移除索引0的元素(变成:[20])
int size = list.size(); // 获取大小(1)
boolean isEmpty = list.isEmpty(); // 是否为空(false)
list.clear();        // 清空列表

Collections.sort(list); // 升序排序
list.sort(Comparator.naturalOrder());

Collections.sort(list, Comparator.reverseOrder()); // 降序排序
list.sort(Comparator.reverseOrder());

list.sort((a, b) -> Integer.compare(Math.abs(a), Math.abs(b))); // 自定义排序,示例按绝对值排序

队列与双端队列,对应 C++ 的 queue、deque

// 队列 (Queue)
Queue<Integer> queue = new LinkedList<>();
queue.offer(10);    // 入队
queue.offer(20);
int head = queue.poll();    // 出队 (10),并获取队首
head = queue.peek();        // 查看队首元素 (20)
boolean isEmpty = queue.isEmpty(); // 是否为空
queue.clear(); // 清空队列
queue.size(); // 队列大小

// 双端队列 (Deque)
Deque<Integer> deque = new ArrayDeque<>();
deque.offerFirst(5);    // 前端插入 (变成:[5, 10])
deque.offerLast(15);    // 后端插入 (变成:[5, 10, 15])
int front = deque.pollFirst(); // 前端移除 (5),并获取元素
int back = deque.pollLast();   // 后端移除 (15),并获取元素

优先队列,对应 C++ priority_queue

// 最小堆(默认)
Queue<Integer> minHeap = new PriorityQueue<>();
minHeap.offer(30);
minHeap.offer(10);
minHeap.offer(20);
int min = minHeap.poll(); // 10
min = minHeap.peek();     // 20

// 最大堆(使用自定义比较器)
Queue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
// 或者: new PriorityQueue<>((a, b) -> b - a);
maxHeap.offer(10);
maxHeap.offer(30);
int max = maxHeap.poll(); // 30

// 自定义对象排序
PriorityQueue<Student> pq = new PriorityQueue<>(
    (s1, s2) -> s1.grade - s2.grade // 按成绩升序
);

栈,对应 C++ stack

Deque<Integer> stack = new ArrayDeque<>();
stack.push(10); // 入栈
stack.push(20);
int top = stack.peek(); // 查看栈顶 (20)
top = stack.pop();      // 出栈 (20)

集合, 对应 C++ set 和 unordered_set

// TreeSet(有序集合 - 红黑树实现)
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(30);
treeSet.add(10);
treeSet.add(20);
treeSet.add(20); // 重复元素被忽略
// 遍历结果为:[10, 20, 30](自然顺序)
boolean contains = treeSet.contains(20); // true
treeSet.remove(10);

// 遍历
for (Integer it : treeSet) {
  System.out.println(it);
}
Iterator<Integer> iterator = treeSet.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

// HashSet(无序集合 - 哈希表实现)
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // 重复元素被忽略

映射, 对应 C++ map 和 unordered_map

// TreeMap(有序映射 - 红黑树实现)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("John", 90);
treeMap.put("Alice", 95);
treeMap.put("Bob", 85);
// 按键排序:{"Alice":95, "Bob":85, "John":90}
int aliceScore = treeMap.get("Alice"); // 95
boolean hasBob = treeMap.containsKey("Bob"); // true

// HashMap(无序映射 - 哈希表实现)
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Orange");

// 遍历Map
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 获取所有键
Set<String> keys = treeMap.keySet();

// 获取所有值
Collection<Integer> values = treeMap.values();
posted @ 2025-07-23 09:52  Natural_TLP  阅读(20)  评论(0)    收藏  举报