如何优化在HashSet中存储访问状态的代码?

时间:2013-09-05 18:07:36

标签: java algorithm optimization hashset

我正在为一些USACO培训问题编写解决方案。不幸的是,即使我在我看来使用了正确的算法(正确的答案,接受解决方案的速度太慢),我的实现也太慢了。这是代码:

public class clocks {

    private static LinkedList<State> queue = new LinkedList<State>();

    private static HashSet<State> set = new HashSet<State>();

    private static PrintWriter out;

    static long cTime = 0;

    private static class State implements Cloneable {
        public int[] clocks;
        public List<Byte> road;

        public State(int[] clocks, List<Byte> road) {
            this.clocks = clocks;
            this.road = road;
        }

        private void makeMove(byte move) {
            int[] currentMoves = moves[move];
            for (int i = 0; i < currentMoves.length; i++) {
                clocks[currentMoves[i]] = (clocks[currentMoves[i]] + 1) % 4;
            }
            road.add(move);
        }

        @Override
        public State clone() {
            int[] clocks = new int[this.clocks.length];
            System.arraycopy(this.clocks, 0, clocks, 0, this.clocks.length);
            List<Byte> road = new ArrayList<Byte>(this.road);
            State newState = new State(clocks, road);
            return newState;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + Arrays.hashCode(clocks);
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            State other = (State) obj;
            if (!Arrays.equals(clocks, other.clocks))
                return false;
            return true;
        }
    }

    private static final int[][] moves = new int[][] {
        {0, 1, 3, 4},
        {0, 1, 2},
        {1, 2, 4, 5},
        {0, 3, 6},
        {1, 3, 4, 5, 7},
        {2, 5, 8},
        {3, 4, 6, 7},
        {6, 7, 8},
        {4, 5, 7, 8}
    };

    private static boolean isValid(int[] clocks) {
        for (int i = 0; i < clocks.length; i++) {
            if (clocks[i] != 0) {
                return false;
            }
        }
        return true;
    }

    private static void bfs() {
        while (!queue.isEmpty()) {
            State currentState = queue.pop();
            if (isValid(currentState.clocks)) {
                for (int i = 0; i <= currentState.road.size() - 1; i++) {
                    System.out.print((currentState.road.get(i) + 1));
                    if (i != currentState.road.size() - 1) {
                        System.out.print(" ");
                    }
                }
                System.out.println("");
                break;
            }
            for (byte i = 0; i < moves.length; i++) {
                State newState = currentState.clone();
                newState.makeMove(i);
                long start = System.currentTimeMillis();
                boolean added = set.add(newState);
                cTime += System.currentTimeMillis() - start;
                if (added) {
                    queue.add(newState);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        BufferedReader f = new BufferedReader(new FileReader("clocks.in"));
        out = new PrintWriter(new BufferedWriter(new FileWriter("clocks.out")));
        int clocks[] = new int[9];
        for (int i = 0; i < 3; i++) {
            StringTokenizer tokenizer = new StringTokenizer(f.readLine());
            int k = i*3;
            for (int j = 0; j < 3; j++) {
                clocks[k + j] = (Integer.valueOf(tokenizer.nextToken()) / 3 ) % 4;
            }
        }
        State state = new State(clocks, new ArrayList<Byte>());
        queue.add(state);
        if (!isValid(clocks)) {
            bfs();
        }
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(cTime);
        f.close();
        out.close();
    }
}

我注意到最吸引人的是将新元素添加到集合(90/200毫秒)并创建新状态(70/200毫秒)。我想知道是否有可能以更有效的方式实现此解决方案(例如,没有State类)。

问题陈述:

  

考虑以3x3阵列排列的9个时钟。目标是找到最小的动作序列,将所有刻度盘返回到12点钟位置。通过下表提供了九种不同的方式来转动时钟表盘。每种方式都称为移动。为每次移动选择1到9的数字,这将使受影响的时钟(见下表)的刻度盘顺时针旋转90度。

1 个答案:

答案 0 :(得分:1)

如果我正确地记住了这个问题,那么我遇到的问题与您所做的相同,因为您写的解决方案实际上并不正确。 :)

这里的关键见解是要意识到按下按钮四次与从未按下按钮相同,而您的代码现在没有实现。由于有九个按钮,每个按钮有四个状态,这是4 ^ 9个要检查的操作,这完全在合理的范围内。希望没有深入研究细节,您可以将其合并到您的BFS中,或者只使用强力算法。