确定图G =(V,E)是否包含负重量循环

时间:2019-04-26 03:49:22

标签: java

在此程序中,我得到了一个输入文本文件,该文件提供了有关加权有向图的信息

  

G =(V,E,w)

输入文件中文本文件的第一行存储V(顶点数)和E(边数)。

以下几行按权重uv存储有关边(uv)的数据。

我正在尝试实现考虑此输入并确定G是否包含负权重循环的代码。

到目前为止,我已经尝试使用 Bellman Ford算法来使它起作用:我首先初始化一个dist[]数组,该数组初始化了从源到所有对象的距离其他顶点的数量非常大(确保src到src为0)。

接下来,我|V| - 1放松所有边缘。

最后,我通过再次遍历边缘数组来检查负重循环,检查是否得到较短的路径。

但是,当我尝试进行第二步来放松边缘时,我不断出现索引超出范围的错误。

注意:要检查下面的代码,只需向下滚动到isNegativeCycle()方法。我还包括了其他一些东西,以防有人需要背景信息。

public class P1 {
//instance variables
static int V;   //number of vertices
static int E;   //number of edges

//vertex class
public class Vertex {
    int ID; //the name of the vertex
}

//edge class
public class Edge {
    Vertex source;  //the source vertex - its a directed graph
    Vertex dest;    //the destination vertex
    int weight; //the weight of the edge
}


//graph class where all the magic happens
public class Graph { 
    //Each graph has an array of edges
    Edge edgearray[];

    //constructor
    public Graph(int n, int m)  {
        V = n;
        E = m;

        edgearray = new Edge[E];
        for (int i = 0; i < E; i++) { 
            edgearray[i] = new Edge();
        }
    }

    //THIS IS THE IMPORTANT METHOD
    public String isNegativeCycle(Graph G, int src) {
        int dist[] = new int[V];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[src] = 0;  //cos the distance from A to A is 0

        //Relax all edges
        for (int i = 1; i <= V-1; i++) { 
            for (int j = 0; j < E; j++) { 
                int u = G.edgearray[j].source.ID; 
                int v = G.edgearray[j].dest.ID; 
                int weight = G.edgearray[j].weight; 

            //THIS IS WHERE I GET THE INDEX OUT OF BOUNDS ERROR    
            if (dist[u]!= Integer.MAX_VALUE && (dist[u]+weight) < dist[v]) { 
                    dist[v] = dist[u]+weight; 
            } 
        } 

        //check for a negative cycle
        for (int a = 0; a < E; a++) { 
            int u = G.edgearray[a].source.ID; 
            int v = G.edgearray[a].dest.ID; 
                double weight = G.edgearray[a].weight;

                if (dist[u] != Integer.MAX_VALUE && dist[u]+weight < dist[v])   {
                return "YES";
            }
        } 


        return "NO";
    }


}//end of graph class


//main method 
public static void main(String[] args) {
    P1 instance = new P1();
    int n;
    int m;
    int counter = 0;
    boolean fl = true;
    String infileName = args[0];
    Graph G = instance.new Graph(V, E);

    File infile = new File(infileName);
    Scanner fileReader = null;
    try {
        fileReader = new Scanner(infile);
        while (fileReader.hasNextLine())    {

            //if we're reading the first line
            if (fl == true) {
                String[] temp = fileReader.nextLine().split(" ");
                n = Integer.parseInt(temp[0]);
                V = n;
                m = Integer.parseInt(temp[1]);
                E = m;
                G = instance.new Graph(V, E);
                fl = false;
            }
            //if we're reading any line other than the first line
            else    {
                String[] temp = fileReader.nextLine().split(" ");
                //G.addEdge(temp[0], temp[1], Double.parseDouble(temp[2]));

                Vertex newsrc = instance.new Vertex();
                Vertex newdest = instance.new Vertex();

                newsrc.ID = Integer.parseInt(temp[0]);
                newdest.ID = Integer.parseInt(temp[1]);

                Edge newEdge = instance.new Edge();
                newEdge.source = newsrc;
                newEdge.dest = newdest;
                newEdge.weight = Integer.parseInt(temp[2]);

                G.edgearray[counter] = newEdge;
                counter++;
            }
        }
    }
    catch (FileNotFoundException e) {
        System.out.println("File not found.");  
    }

    System.out.println(G.isNegativeCycle(G, 0));
}
}

目前我当前的输入文件并不重要,但是运行此代码后,我希望输出为“ YES”。谢谢!

1 个答案:

答案 0 :(得分:0)

我应该包括我的输入文件。在我的输入文件中,您会看到顶点名称从1开始。因此,在调用import pygame #####IMPORTING PYGAME MODULE########################### pygame.init() #####INITIALIZINGPYGAME################################## gameWindow = pygame.display.set_mode((800,600)) ###Screen Width and Height### clock = pygame.time.Clock() ## FRAMES PER SECOND ## white = (255,255,255) black = (0,0,0) def player(px,py): pygame.draw.rect(gameWindow,black,[px,py,30,30]) def missile(mx,my): pygame.draw.rect(gameWindow,black,[mx,my,10,10]) def gameloop(): px = 700 py = 300 mx = 700 my = 300 px_change = 0 py_change = 0 mx_change = 0 my_change = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: mx_change = -10 if event.key == pygame.K_RIGHT: mx_change = 10 if event.key == pygame.K_UP: my_change = -10 if event.key == pygame.K_DOWN: my_change = 10 if event.key == pygame.K_SPACE: mx_change = -100 if event.key == pygame.K_LEFT: px_change = -10 if event.key == pygame.K_RIGHT: px_change = 10 if event.key == pygame.K_UP: py_change = -10 if event.key == pygame.K_DOWN: py_change = 10 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: px_change = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: py_change = 0 if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: mx_change = 0 mx = px if event.key == pygame.K_UP or event.key == pygame.K_DOWN: my_change = 0 my = py if event.key == pygame.K_SPACE: mx_change = 0 my_change = 0 mx = px my = py px += px_change py += py_change mx += mx_change my += my_change gameWindow.fill(white) player(px,py) missile(mx,my) pygame.display.update() clock.tick(15) gameloop() 时,我应该发送的是1而不是0。此外,我制作的是isNegativeCycle排列大一号。