uva136 java

107 阅读1分钟

暴力法超时了,这个优先级队列还是第一次接触到,很好用。

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

public class Main {

    public static void main(String[] args) {
        solution(System.in, new MyPrinter());
    }

    public static void solution(InputStream in, Printer p) {
        int[] factors = new int[]{2, 3, 5};
        int count = 1;
        long number;
        HashSet<Long> ns = new HashSet<>();
        PriorityQueue<Long> pq = new PriorityQueue<>();
        ns.add(1L);
        pq.add(1L);
        while (true) {
            number = pq.poll();
            if (count == 1500) {
                p.pn("The 1500'th ugly number is %d.", number);
                break;
            }
            count ++;
            for(int f : factors) {
                long x = number * f;
                if (!ns.contains(x)) {
                    ns.add(x);
                    pq.add(x);
                }
            }
        }

    }

interface Printer {
    void p(Object... o);

    void pn(Object... o);

    default String format(Object... o) {
        String format;
        if (o.length == 1) {
            format = o[0].toString();
        } else {
            Object[] dest = new Object[o.length - 1];
            System.arraycopy(o, 1, dest, 0, dest.length);
            format = String.format(o[0].toString(), dest);
        }
        return format;
    }
}

class MyPrinter implements Printer {
    @Override
    public void p(Object... o) {
        System.out.print(format(o));
    }

    @Override
    public void pn(Object... o) {
        if ("true".equals(System.getenv("OUTPUT_TO_LOCAL"))){
            try {
                if (o.length != 0) {
                    writer.write(format(o));
                }
                writer.write("\n");
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (o == null || o.length == 0) {
            System.out.println();
        } else {
            System.out.println(format(o));
        }
    }

    private static FileWriter writer;
    static {
        try {
            writer = new FileWriter("D:\\output.txt");
            writer.write("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}