-3

任何避免此问题超过时间限制的提示:_ http://www.spoj.com/problems/BUGLIFE/

我该如何优化这段代码

有没有更快的读取输入的方法

这些是我阅读输入的方法:_ http://ideone.com/GtSIAC

我的解决方案:_

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

public class buglife {
    static int first;
    static ArrayList[] graph = new ArrayList[2000];
    static int[] colour = new int[2000];
    static int[] queue = new int[2000];
    static int start;
    static int index;
    static int current;

    public static boolean bfs(int f) {  
        for (int p = 0; p < first; p++) {
        if (colour[p] != f && colour[p] != f + 1) {
        int x;
        start = 0;
        index = 0;
        queue[index++] = p;
        colour[p] = f;


            while (start < index) {
                    current = queue[start++];
                    for (int i = 0; i < graph[current].size(); i++) {
                        x = (Integer) graph[current].get(i);
                        if (colour[x] != f && colour[x] != f + 1) {
                            if (colour[current] == f) {
                                colour[x] = f + 1;
                            } else if (colour[current] == f + 1) {
                                colour[x] = f;
                            }

                            queue[index++] = x;
                        } else if (colour[current] == colour[x]) {

                            return false;
                        }

                    }
                }

            }
        }
        return true;
    }

    public static void main(String[] args) throws IOException, Exception {
        int second;
        int one, two;
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(System.out)));

        int test = nextInt();
        int j, k, i;
        for (i = 1; i <= test; i++) {
            first = nextInt();
            second = nextInt();
            for (k = 0; k < first; k++)
                graph[k] = new ArrayList();

            for (j = 0; j < second; j++) {

                one = nextInt();
                two = nextInt();
                graph[one - 1].add(two - 1);
                graph[two - 1].add(one - 1);
            }

            out.println("Scenario #" + i + ":");
            if (bfs( 2 * i) == false) {
                out.println("Suspicious bugs found!");
            } else {
                out.println("No suspicious bugs found!");
            }

        }
        out.flush();
    }




}
4

1 回答 1

0

你不能只使用 bfs 来解决它,这个问题是关于二分图的

看看维基百科就知道了

一年多前我解决了这个问题。我的简历

于 2013-08-04T01:46:17.393 回答