prefix(2)

来源:互联网 发布:discuz 标签 seo 编辑:程序博客网 时间:2024/06/10 19:04
/*ID: daniel.20LANG: JAVATASK: prefix */import java.io.*;import java.util.*;public class prefix {    static ArrayList<String> prims = new ArrayList<String>();    static char target[] = new char[200002];    static int table[];    public static void initial() throws Exception {        BufferedReader f = new BufferedReader(new FileReader("prefix.in"));        while (true) {            String tmp = f.readLine();            if (tmp.equals(".")) {                break;            }            StringTokenizer st = new StringTokenizer(tmp);            while (st.hasMoreTokens()) {                prims.add(st.nextToken());            }        }        String tmp = "";        int start = 0;        while((tmp=f.readLine())!=null){            for(int i=0;i<tmp.length();++i)                target[start+i]=tmp.charAt(i);            start+=tmp.length();        }        table = new int[target.length + 1];        Arrays.fill(table, 99999);        table[0] = 0;    }    public static boolean matchString(int t, String tmp) {        if (tmp.length() > t) {            return false;        }        for (int j = tmp.length() - 1; j >= 0; --j) {            if (tmp.charAt(j) != target[t - tmp.length() + j]) {                return false;            }        }        return true;    }    public static void dp() throws Exception {        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("prefix.out")));        for (int i = 1; i < table.length; ++i) {            for (int j = 0; j < prims.size(); ++j) {                String tmp = prims.get(j);                if (matchString(i, tmp)) {                    if (table[i - tmp.length()] == 0) {                        table[i] = 0;                        break;                    }                }            }        }        for (int i = table.length - 1; i >= 0; --i) {            if (table[i] == 0) {                out.println(i);                out.close();                break;            }        }    }    public static void main(String[] args) throws Exception {        long t1 = System.currentTimeMillis();        initial();        dp();        System.out.println(System.currentTimeMillis() - t1);        System.exit(0);    }}


总算找到了为什么读入那么慢,图省事,用了 s+=f.readLine();

不是很确定,估计要查下API,估计String有默认的空间,不停加入超过额定空间,估计需要重新分配内存,这就很耗时间了,以前A题不知道是数据量小,还是没这么简单的用string就能保存,不记得了,没遇到过这个情况。

改过之后算法很快就出来了,对于最大的test case反而只要0.2s......至少哥的算法是efficent的

Test 1: TEST OK [0.162 secs, 30048 KB]

Test 2: TEST OK [0.144 secs, 30048 KB]

Test 3: TEST OK [0.396 secs, 30048 KB]

Test 4: TEST OK [0.450 secs, 30048 KB]

Test 5: TEST OK [0.666 secs, 30048 KB]

Test 6: TEST OK [0.234 secs, 30048 KB] 

原创粉丝点击