CodeChef March Challenge 2015 - TREECNT2

本番解けなかったので復習した。 TREECNT2 - Editorial - CodeChef Discuss と同じ方針で書いたつもりだけど、自分の書き方が悪いせいかTLEが厳しかった。

これくらい複雑だと、コーディングする最中に混乱してくるし、デバッグも机上だと辛くなってくる。

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

import static java.util.Arrays.*;

public class Main implements Runnable {
// private static final int mod = (int)1e9+7;
// private static final int mod = 104857601;

    static final boolean debug = false;
    final Random random = new Random(0);
    final IOFast io = new IOFast();

    /// MAIN CODE
    @Override
    public void run() {
        try {
            runMain();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private void runMain() throws IOException {
        if(debug) {
            while(true) searchBadCase();
        }
        
//     int TEST_CASE = Integer.parseInt(new String(io.nextLine()).trim());
        int TEST_CASE = 1;
        while(TEST_CASE-- != 0) {
            n = io.nextInt();
            es = new int[n-1][];
            for(int i = 0; i < n - 1; i++) {
                int s, t, w;
                s = io.nextInt() - 1;
                t = io.nextInt() - 1;
                w = io.nextInt();
                es[i] = new int[]{s,t,w,};
            }
            
            Qs = new int[io.nextInt()][2];
            for(int i = 0; i < Qs.length; i++) {
                Qs[i][0] = io.nextInt() - 1;
                Qs[i][1] = io.nextInt();
            }

            for(long v : solve()) {
                io.out.println(v);
            }
        }
    }
    
    long[] solve() {
        int[][] gi = new int[MAX_L+1][];
        int[][] gq = new int[MAX_L+1][];
        List<Integer>[] tmpG = new List[MAX_L+1];
        for(int i = 0; i < gi.length; i++) {
            tmpG[i] = new ArrayList<Integer>();
        }

        int[] moebius = moebiusMu(MAX_L);
        final int[] factor = new int[256];
        for(int i = 0; i < es.length; i++) {
            final int len = getFactor(factor, es[i][2]);
            for(int j = 0; j < len; j++) {
                tmpG[factor[j]].add(i);
            }
        }
        for(int i = 2; i <= MAX_L; i++) {
            gi[i] = new int[tmpG[i].size()];
            for(int j = 0; j < gi[i].length; j++) {
                gi[i][j] = tmpG[i].get(j);
            }
            tmpG[i].clear();
        }
        
        for(int i = 0; i < Qs.length; i++) {
            final int len = getFactor(factor, Qs[i][1]);
            for(int j = 0; j < len; j++) {
                tmpG[factor[j]].add(i);
            }
        }
        for(int i = 2; i <= MAX_L; i++) {
            gq[i] = new int[tmpG[i].size()];
            for(int j = 0; j < gq[i].length; j++) {
                gq[i][j] = tmpG[i].get(j);
            }
        }
        
        int gid = 0;
        final int[] vid = new int[MAX_N];
        final int[] vid2 = new int[MAX_N];
        final int[] vindex_vi = new int[MAX_N];
        final int[] vindex_iv = new int[MAX_N];
        final int[] vindex_vi2 = new int[MAX_N];
        final int[] vindex_iv2 = new int[MAX_N];
        final int[] eid_q = new int[MAX_N];
        final int[] eid_union = new int[MAX_N];
        final long[] ans = new long[Qs.length+1];
        final UnionFind_ClearFast_Sum uf = new UnionFind_ClearFast_Sum(n);
        final UnionFind_ClearFast_Sum uf2 = new UnionFind_ClearFast_Sum(n);
        
        Arrays.fill(ans, n * (n - 1L) / 2);
        
        for(int i = 2; i <= MAX_L; i++) if(gi[i].length > 0 || gq[i].length > 0) {
            gid++;
            
            for(final int e[] : Qs) {
                eid_q[e[0]] = gid;
            }
            
            int vsize = 0;
            for(final int e : gi[i]) {
                for(int j = 0; j < 2; j++) {
                    final int k = es[e][j];
                    if(vid[k] != gid) {
                        vid[k] = gid;
                        vindex_iv[vsize] = k;
                        vindex_vi[k] = vsize++;
                    }
                }
            }
            for(final int e : gq[i]) {
                for(int j = 0; j < 2; j++) {
                    final int k = es[Qs[e][0]][j];
                    if(vid[k] != gid) {
                        vid[k] = gid;
                        vindex_iv[vsize] = k;
                        vindex_vi[k] = vsize++;
                    }
                }
            }
            
            uf.clear();
            for(final int e : gi[i]) {
                if(eid_q[e] != gid) {
                    uf.union(vindex_vi[es[e][0]], vindex_vi[es[e][1]]);
                }
                else {
                    eid_union[e] = gid;
                }
            }
            
            int vsize2 = 0;
            for(int j = 0; j < vsize; j++) {
                final int r = uf.root(j);
                if(vid2[r] != gid) {
                    vid2[r] = gid;
                    vindex_iv2[vsize2] = r;
                    vindex_vi2[r] = vsize2++;
                }
                vindex_vi2[j] = vindex_vi2[r];
            }
            
            long prevVal = Long.MIN_VALUE;
            for(int q = 0, gq_idx = 0; q <= Qs.length; q++) {
                if(prevVal == Long.MIN_VALUE) {
                    uf2.clear();
                    
                    for(int j = 0; j < vsize2; j++) {
                        uf2.setSum(j, uf.size(vindex_iv2[j]));
                    }
                    
                    for(final int[] qe : Qs) {
                        final int e = qe[0];
                        if(eid_union[e] == gid) {
                            final int a = vindex_vi2[vindex_vi[es[e][0]]];
                            final int b = vindex_vi2[vindex_vi[es[e][1]]];
                            uf2.union(a, b);
                        }
                    }
                    
                    prevVal = 0;
                    for(int j = 0; j < vsize2; j++) {
                        if(uf2.root(j) == j) {
                            final int v = uf2.getSum(j);
                            prevVal += moebius[i] * v * (v - 1L) / 2;
                        }
                    }
                }
                ans[q] += prevVal;
                
                if(q != Qs.length) {
                    boolean prevCond = eid_union[Qs[q][0]] == gid;
                    if(gq_idx < gq[i].length && gq[i][gq_idx] == q) {
                        gq_idx++;
                        eid_union[Qs[q][0]] = gid;
                    }
                    else {
                        eid_union[Qs[q][0]] = gid - 1;
                    }
                    boolean curCond = eid_union[Qs[q][0]] == gid;
                    if(prevCond != curCond) {
                        prevVal = Long.MIN_VALUE;
                    }
                }
            }
        }
        
        return ans;
    }
    
    int[] tmpGetFactor = new int[32];
    int getFactor(final int[] factor, int v) {
        int len = 0;
        for(; v != 1; ) {
            final int d = minDiv[v];
            tmpGetFactor[len++] = d;
            while(d == minDiv[v]) {
                v /= minDiv[v];
            }
        }
        int len2 = 0;
        for(int j = 1; j < 1 << len; j++) {
            int v2 = 1;
            for(int k = 0; k < len; k++) {
                if((j>>>k&1)==1) {
                    v2 *= tmpGetFactor[k];
                }
            }
            factor[len2++] = v2;
        }
        return len2;
    }

    final int MAX_N = 100000;
    final int MAX_L = 1000000;
    int n;
    int[][] es;
    int[][] Qs;
    int[] minDiv = minDivisor(MAX_L+1);
    
    // [0,n]
    int[] moebiusMu(int n) {
        int[] ret = new int[n+1];
        ret[1] = 1;
        for(int i = 2; i < ret.length; i++) {
            if(minDiv[i/minDiv[i]] == minDiv[i]) {
                // square
                ret[i] = 0;
            }
            else {
                ret[i] = -ret[i/minDiv[i]];
            }
        }
        return ret;
    }
    
    private static int[] minDivisor(int n) {
        final int[] min = new int[n+1];
        min[0] = min[1] = 1;
        for(int i = 2; i*i <= n; i++) {
            if(min[i] == 0) {
                min[i] = i;
                for(int j = i*i; j <= n; j += i) {
                    if(min[j] == 0) {
                        min[j] = i;
                    }
                }
            }
        }
        for(int i = 2; i <= n; i++) {
            if(min[i] == 0) {
                min[i] = i;
            }
        }
        return min;
    }
    
    static
    class UnionFind_ClearFast_Sum {
        private int gid;
        private int[] id;
        private int[] data;
        private int[] val;
        
        public UnionFind_ClearFast_Sum(int size) {
            data = new int[size];
            id = new int[size];
            val = new int[size];
            clear();
        }
        
        public void clear() {
            gid++;
        }
        public void setSum(int x, int v) { val[root(x)] = v; }
        public int getSum(int x) { return val[root(x)]; }
        
        private void access(int x) { if(gid != id[x]) { id[x] = gid; data[x] = -1; } }
        public int root(int x) { access(x); return data[x] < 0 ? x : (data[x] = root(data[x])); }
        
        public void union(int x, int y) {
            if((x = root(x)) != (y = root(y))) {
                if(data[y] < data[x]) { final int t = x; x = y; y = t; }
                data[x] += data[y];
                data[y] = x;
                val[x] += val[y];
            }
        }
        
        public boolean same(int x, int y) { return root(x) == root(y); }
        public int size(int x) { return -data[root(x)]; }
    }

    // for debug
    void searchBadCase() {
        n = 10;
        es = new int[n-1][];
        for(int i = 0; i < n - 1; i++) {
            int s, t, w;
            s = i + 1;
            t = random.nextInt(i + 1);
            w = random.nextInt(10)+1;
            es[i] = new int[]{s,t,w,};
        }
        
        Qs = new int[3][2];
        for(int i = 0; i < Qs.length; i++) {
            Qs[i][0] = random.nextInt(n-1);
            Qs[i][1] = random.nextInt(10)+1;
        }

        long[] res = solve();
        long[] res2 = naive();
        if(!Arrays.equals(res, res2)) {
            System.err.println(Arrays.deepToString(es));
            System.err.println(Arrays.deepToString(Qs));
            System.err.println(Arrays.toString(res));
            System.err.println(Arrays.toString(res2));
            throw new RuntimeException();
        }
        System.err.println("ok");
    }
    
    long[] naive() {
        int[][] es2 = new int[n-1][3];
        for(int i = 0; i < n - 1; i++) {
            for(int j = 0; j < es[i].length; j++) {
                es2[i][j] = es[i][j];
            }
        }
        long[] res = new long[Qs.length+1];
        for(int i = 0; i <= Qs.length; i++) {
            for(int j = 0; j < n; j++) {
                res[i] += dfs(es2, j, -1, 0);
            }
            res[i] /= 2;
            if(i != Qs.length) {
                es2[Qs[i][0]][2] = Qs[i][1];
            }
        }
        return res;
    }
    
    int dfs(int[][] es2, int v, int p, int g) {
        int res = 0;
        if(g == 1) res++;
        for(int i = 0; i < es2.length; i++) {
            for(int j = 0; j < 2; j++) {
                if(es2[i][j] == v && es2[i][j^1] != p) {
                    res += dfs(es2 ,es2[i][j^1], v, gcd(g, es2[i][2]));
                }
            }
        }
        return res;
    }
    
    /// TEMPLATE
    static int gcd(int n, int r) { return r == 0 ? n : gcd(r, n%r); }
    static long gcd(long n, long r) { return r == 0 ? n : gcd(r, n%r); }
    
    static <T> void swap(T[] x, int i, int j) { T t = x[i]; x[i] = x[j]; x[j] = t; }
    static void swap(int[] x, int i, int j) { int t = x[i]; x[i] = x[j]; x[j] = t; }
    
    void main() throws IOException, InterruptedException {
        //     IOFast.setFileIO("rle-size.in", "rle-size.out");
        try {
            Thread thread = new Thread(null, this, "0", 1<<25);
            thread.start();
            thread.join();
//         run();
        }
        catch (EndOfFileRuntimeException e) { }
        io.out.flush();
    }
    public static void main(String[] args) throws IOException, InterruptedException { new Main().main(); }
    
    static class EndOfFileRuntimeException extends RuntimeException {
        private static final long serialVersionUID = -8565341110209207657L; }

    static
    public class IOFast {
        private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        private PrintWriter out = new PrintWriter(System.out);

        void setFileIn(String ins) throws IOException { in.close(); in = new BufferedReader(new FileReader(ins)); }
        void setFileOut(String outs) throws IOException { out.flush(); out.close(); out = new PrintWriter(new FileWriter(outs)); }
        void setFileIO(String ins, String outs) throws IOException { setFileIn(ins); setFileOut(outs); }

        private static int pos, readLen;
        private static final char[] buffer = new char[1024 * 8];
        private static char[] str = new char[500*8*2];
        private static boolean[] isDigit = new boolean[256];
        private static boolean[] isSpace = new boolean[256];
        private static boolean[] isLineSep = new boolean[256];

        static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; }
        public int read() throws IOException { if(pos >= readLen) { pos = 0; readLen = in.read(buffer); if(readLen <= 0) { throw new EndOfFileRuntimeException(); } } return buffer[pos++]; }
        public int nextInt() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; }
        public long nextLong() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; long ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; }
        public char nextChar() throws IOException { while(true) { final int c = read(); if(!isSpace[c]) { return (char)c; } } }
        int reads(int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } if(str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; }
        int reads(char[] cs, int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } cs[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; }
        public char[] nextLine() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isLineSep); try { if(str[len-1] == '\r') { len--; read(); } } catch(EndOfFileRuntimeException e) { ; } return Arrays.copyOf(str, len); }
        public String nextString() throws IOException { return new String(next()); }
        public char[] next() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); return Arrays.copyOf(str, len); }
        public int next(char[] cs) throws IOException { int len = 0; cs[len++] = nextChar(); len = reads(cs, len, isSpace); return len; }
        public double nextDouble() throws IOException { return Double.parseDouble(nextString()); }
        public long[] nextLongArray(final int n) throws IOException { final long[] res = new long[n]; for(int i = 0; i < n; i++) { res[i] = nextLong(); } return res; }
        public int[] nextIntArray(final int n) throws IOException { final int[] res = new int[n]; for(int i = 0; i < n; i++) { res[i] = nextInt(); } return res; }
        public int[][] nextIntArray2D(final int n, final int k) throws IOException { final int[][] res = new int[n][]; for(int i = 0; i < n; i++) { res[i] = nextIntArray(k); } return res; }
        public int[][] nextIntArray2DWithIndex(final int n, final int k) throws IOException { final int[][] res = new int[n][k+1]; for(int i = 0; i < n; i++) { for(int j = 0; j < k; j++) { res[i][j] = nextInt(); } res[i][k] = i; } return res; }
        public double[] nextDoubleArray(final int n) throws IOException { final double[] res = new double[n]; for(int i = 0; i < n; i++) { res[i] = nextDouble(); } return res; }
    }
}